Call a C# method/function from a C++ DLL (which is loaded from C# with “Dllimport”)

前端 未结 4 782
逝去的感伤
逝去的感伤 2021-01-22 00:21

It\'s a little hard to resume it in a single title, so here my situation.

I\'m building a C# application that loads a C++ library.
I call functions from that C++ DLL

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-22 01:11

    Here's my answer to this question, which was similar. My example doesn't use arguments for the callback. Since your arguments are integers, though, you shouldn't have any problems.

    Basically, the Marshal.GetFunctionPointerForDelegate method creates an IntPtr from a delegate. That delegate should have the same signature as the function pointer used in your C++ library.

    // This is the delegate type that we use to marshal
    // a function pointer for C to use. You usually need
    // to specify the calling convention so it matches the
    // convention of your C library. The signature of this
    // delegate must match the signature of the C function
    // pointer we want to use.
    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    delegate void FunctionPointer();
    
    // This is the function we import from the C library.
    [DllImport(dllFilePath)]
    static extern void callCSharpFunction(IntPtr fctPointer);
    
    // This is the placeholder for the function pointer
    // we create using Marshal.GetFunctionPointerForDelegate
    IntPtr FctPtr;
    
    // This is the instance of the delegate to which our function
    // pointer will point.
    FunctionPointer MyFunctionPointer;
    
    // This calls the specified delegate using the C library.
    void CallFunctionPointer(FunctionPointer cb)
    {
        // make sure the delegate isn't null
        if (null == cb) throw new ArgumentNullException("cb");
    
        // set our delegate place holder equal to the specified delegate
        MyFunctionPointer = cb;
    
        // Get a pointer to the delegate that can be passed to the C library
        FctPtr = Marshal.GetFunctionPointerForDelegate(MyFunctionPointer );
    
        // call the imported function with that function pointer.
        callCSharpFunction(FctPtr);
    } 
    

提交回复
热议问题