Pass a function pointer from C++ to be called by C# - Arguments of functions include a wide char string (LPCWSTR)

后端 未结 2 876
栀梦
栀梦 2020-12-19 21:15

I am writing a C# library to be used by native C++ application. I am using C++/CLI as the Interoperability mechanisim.

I require to pass a callback function from C++

相关标签:
2条回答
  • 2020-12-19 21:54

    See the little-known UnmanagedFunctionPointer attribute, which is like DllImport for delegates, if you'd like to use CharSet or whatnot.

    0 讨论(0)
  • 2020-12-19 21:59

    GetDelegateForFunctionPointer will work, but you need to add a [MarshalAs(UnmanagedType.LPWStr)] attribute to the parameter in your delegate declaration in order for String to get converted into wchar_t*:

    delegate void MyDelegate([MarshalAs(UnmanagedType.LPWStr)] string foo)
    
    IntPtr func = ...;
    MyDelegate del = (MyDelegate)Marshal.GetDelegateForFunctionPointer(func,
                                     typeof(MyDelegate));
    

    To pass a modifiable string, give a StringBuilder. You need to explicitly reserve space for the unmanaged function to work with:

    delegate void MyDelegate([MarshalAs(UnmanagedType.LPWStr)] StringBuilder foo)
    
    StringBuilder sb = new StringBuilder(64); // reserve 64 characters.
    
    del(sb);
    
    0 讨论(0)
提交回复
热议问题