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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/508227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 06:09:43  来源:igfitidea点击:

How to import const char* API to C#?

c#dllimport

提问by Mike Chess

Given this C API declaration how would it be imported to C#?

鉴于此 C API 声明,它将如何导入到 C#?

const char* _stdcall z4LLkGetKeySTD(void);

I've been able to get this far:

我已经能够做到这一点:

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

采纳答案by JaredPar

Try this

尝试这个

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

You can then convert the result to a String by using Marshal.PtrToStringAnsi(). You will still need to free the memory for the IntPtr using the appropriate Marshal.Free* method.

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

回答by Cody Brocious

Just use 'string' instead of 'const char *'.

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

Edit: This is dangerous for the reason JaredPar explained. If you don't want a free, don't use this method.

编辑:由于 JaredPar 解释的原因,这很危险。如果您不想要免费,请不要使用此方法。

回答by Robert

Always use C++ const char* or char* and not std::string.

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

Also keep in mind that char in C++ is a sbyte in C# and unsigned char is a byte in C#.

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

It is advisable to use unsafe code when dealing with DllImport.

建议在处理 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());
 }