Calling C DLL from C#

后端 未结 4 1425
悲哀的现实
悲哀的现实 2020-12-14 23:47

I am trying to call a C DLL from C#, but I\'m not having any joy. The documentation for the DLL provides an example function delaration for VB that looks like;



        
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-15 00:04

    I found the reason for my failed attempts by utilising a tool called; Microsoft(R) P/Invoke Interop Assistant as suggested by an answer on this thread.

    I utilised this tool to input some of the C function prototypes and get it to generate the required C# prototype on my behalf. The C prototype looked like the following;

    long __stdcall TransProjPt(LPSTR psGridFile, long lDirection, double dEasting, double
    dNorthing, long lZone, double* pdEastNew, double* pdNorthNew, double* pdEastAcc,
    double* pdNorthAcc) 
    

    When entering this into the Interop assistant tool, it showed that rather than using longs (as I had done in my original question), these should be declared as an int. It produced the following output that meant my code above now worked as I'd hoped. Yay.

        /// Return Type: int
        ///psGridFile: LPSTR->CHAR*
        ///lDirection: int
        ///dEasting: double
        ///dNorthing: double
        ///lZone: int
        ///pdEastNew: double*
        ///pdNorthNew: double*
        ///pdEastAcc: double*
        ///pdNorthAcc: double*
        [System.Runtime.InteropServices.DllImportAttribute("", EntryPoint="TransProjPt", CallingConvention=System.Runtime.InteropServices.CallingConvention.StdCall)]
    public static extern  int TransProjPt([System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)] System.Text.StringBuilder psGridFile, int lDirection, double dEasting, double dNorthing, int lZone, ref double pdEastNew, ref double pdNorthNew, ref double pdEastAcc, ref double pdNorthAcc) ;
    

    Thanks for everyones help with this.

提交回复
热议问题