Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
784 views
in Technique[技术] by (71.8m points)

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

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++ to C# (using C++/CLI as the intermediate layer). C# library needs to call the C++ function with a zero terminated string of wide characters; i.e. the prototype of the callback function is

Func(LPCWSTR pszString);

There are other parameters but they are immaterial for this discussion.

I searched net and found Marshal.GetDelegateForFunctionPointer Method wich I can use. The problem with this is that it converts System.String from C# to char* and not wchar_t* which I am looking for.

Also, what is the best method of achieving this- code example including the C++/CLI portion, if possible. C++/CLI dll is dependent on C# dll. Method needs to be called synchronously.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...