C# 从 c++ 获取字符串/字符值返回 char 指针的函数
我有一个用 C++ 编写的 DLL。该 DLL 的函数类似于以下代码:
C++ 代码:
char _H *GetPalette() {
-------Functions body
-------Functions body
return pPaletteString;
}
现在我想从 C# 代码中的 GetPalette() 函数获取 Pallet String。
我如何从该函数中获取字符串? 我已经在 C# 代码中尝试过这个。但无法得到正确的结果。
C# 代码:
[DllImport("cl.dll", EntryPoint = "GetPalette@0", CallingConvention = CallingConvention.StdCall)]
private static extern IntPtr libGetPalette();
public IntPtr GetPalette()
{
return libGetPalette();
}
最后我想得到这样的字符串
IntPtr result;
result = imgProcess.GetPallet();
string pallet;
pallet = Marshal.PtrToStringAnsi(result);
MessageBox.Show(pallet);
此代码无法正常工作。 有人可以帮我吗,我怎样才能从我的 C++ DLL 函数中获取字符串值?
谢谢沙赫里亚尔
I've a DLL written in C++. A function of this DLL is like the following code:
C++ code:
char _H *GetPalette() {
-------Functions body
-------Functions body
return pPaletteString;
}
Now I want to get the Pallet String from that GetPalette() function in C# code.
How could I get string from that function?
I've tried this in C# code. But could not get the correct result.
C# code:
[DllImport("cl.dll", EntryPoint = "GetPalette@0", CallingConvention = CallingConvention.StdCall)]
private static extern IntPtr libGetPalette();
public IntPtr GetPalette()
{
return libGetPalette();
}
Finally I want to get string like this
IntPtr result;
result = imgProcess.GetPallet();
string pallet;
pallet = Marshal.PtrToStringAnsi(result);
MessageBox.Show(pallet);
This code does not work properly.
Can some body plz help me, How could I get the string value from my C++ DLL function?
Thanks
Shahriar
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用字符串返回类型在 C# 代码中定义 C++ 函数。
而不是简单地从 C# 代码中调用它。
在
DllImport
属性中,您可能需要设置正确的调用约定CallingConvention
和字符编码CharSet
You can define your C++ function in C# code with string return type.
And than simply call it from in your C# code.
Within
DllImport
attribute you might need to set correct calling conventionCallingConvention
and character encodingCharSet
您已经告诉 C# 调用约定是
__stdcall
,但没有证据表明函数本身有__stdcall
标记。此外,char*
可以是 UTF-8。You've told C# that the calling convention is
__stdcall
but there's no evidence of__stdcall
marking on the function itself. In addition,char*
could be UTF-8.