Csharp/C#教程:如何将const char * API导入C#?分享


如何将const char * API导入C#?

鉴于此C API声明如何将其导入C#?

const char* _stdcall z4LLkGetKeySTD(void); 

我已经能够做到这一点:

  [DllImport("zip4_w32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "z4LLkGetKeySTD", ExactSpelling = false)] private extern static const char* z4LLkGetKeySTD(); 

试试这个

  [DllImport("zip4_w32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "z4LLkGetKeySTD", ExactSpelling = false)] private extern static IntPtr z4LLkGetKeySTD(); 

然后,您可以使用Marshal.PtrToStringAnsi()将结果转换为String。 您仍然需要使用适当的Marshal.Free *方法释放IntPtr的内存。

始终使用C ++ const char *或char *而不是std :: string。

还要记住,C ++中的char是C#中的sbyte,而unsigned char是C#中的一个字节。

在处理DllImport时,建议使用不安全的代码。

 [DllImport("zip4_w32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "z4LLkGetKeySTD", ExactSpelling = false)] private extern static sbyte* or byte* z4LLkGetKeySTD(); void foo() { string res = new string(z4LLkGetKeySTD()); } 

只需使用’string’而不是’const char *’。

编辑:这是危险的,因为JaredPar解释说。 如果您不想免费,请不要使用此方法。

上述就是C#学习教程:如何将const char * API导入C#?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请点击右边联系管理员删除。

如若转载,请注明出处:https://www.ctvol.com/cdevelopment/1014763.html

(0)
上一篇 2021年12月31日
下一篇 2021年12月31日

精彩推荐