将字符串传递给dll
问题描述:
如何使用字符串参数从C#WPF应用程序调用C++ dll中的函数?我通过“添加引用”添加DLL到C#应用程序,而不是“[DLLImport]”将字符串传递给dll
所有问题是,C#建议函数与'sbyte *'参数,而不是'char *'。 'int'参数的函数是完美的。
这里是代码:
我在c函数++ DLL:
public ref class OpenGLHwnd : public HwndHost
{
public:
void myFunc(char* name)
{
// some code
}
C#代码:
HwndHost host = new WPFOpenGLLib.OpenGLHwnd();
HWNDPlaceholder.Child = host;
(HWNDPlaceholder.Child as WPFOpenGLLib.OpenGLHwnd).myFunc("aaaa");
myFunc的希望 '为sbyte *' parametr,而不是 '字符*'。为什么?
或者告诉请,如何将字符串转换到sbyte *
答
因为你的C++ DLL显然是一个.NET程序集(ref class
,即C++/CLI),你可以把这个字符串作为.NET String
:
#include <msclr/marshal.h>
using namespace msclr::interop;
public ref class OpenGLHwnd : public HwndHost
{
public:
void myFunc(System::String^ name)
{
marshal_context^ context = gcnew marshal_context();
const char* ptr = context->marshal_as<const char*>(name);
puts(ptr);
delete context;
}