PInvoke with a CString

北城余情 提交于 2019-12-02 19:51:12

问题


I'm trying to use P/Invoke to call functions in an unmanaged C++ DLL from C#. The C++ DLL uses CString's as function parameters and returns, such as

CString AFX_EXT_API GetUserName(CString& userID)

Unfortunately, the C++ is legacy code that I cannot change to use the more universal LPSTR (or even char *).

Is there any way to marshal the CString into a .NET compatible object? Or somehow decorate a .NET char[] to be marshaled to a CString?


回答1:


You can't create a CString in managed code. So clearly you need an extra layer between the managed code and the native code.

This gives you an opportunity to make a C++/CLI DLL which sits between. You can call this code from your managed assembly without needing P/invoke. And from the C++/CLI middle layer you can create a CString.

However, there is one caveat. You must be using the same C++ runtime as the native DLL. This may be possible but it is quite likely that it will be a stumbling block. For example if the DLL was written with MSVC6 then you will need to build your intermediate layer with MSVC6 too and that rules out C++/CLI. Back to P/invoke and char* in that case.

I would stress that it is terrible practice to export a DLL interface based on CString and I'd be looking for alternatives to the DLL.




回答2:


If you can't change the DLL itself, the obvious choice is writing a proxy DLL which would accept char[], allocate a CString and then call the DLL.



来源:https://stackoverflow.com/questions/7618130/pinvoke-with-a-cstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!