[英]C# DllImport and Marshaling char**
I'm working in c# and I need to use this function from a c++ dll: 我正在使用C#,并且需要从C ++ dll使用此函数:
extern "C" char IMPEXP __stdcall service_GetParameter ( const char* parameter, const int value_lenght, char** value );
I have used it in c++ code as follow: 我已经在c ++代码中使用了它,如下所示:
char *val = new char[256];
service_GetParameter("firmware_version", 255, &val);
AnsiString FirmwareVersion = val;
delete[] val;
How can I import this function and use it in c#? 如何导入此函数并在c#中使用它?
Thanks in advance 提前致谢
If this function allocates memory and makes the caller responsible for freeing it, I'm afraid you'll have to manage this manually: Declare the parameter as a ref IntPtr
and use the methods of the Marshal
class to get a String with a copy of the pointed data. 如果此函数分配了内存并使调用者负责释放它,那么恐怕您将不得不手动进行管理:将参数声明为ref IntPtr
并使用Marshal
类的方法获取具有以下内容的String的字符串:指向的数据。
Then call the appropriate function for freeing the memory (as Dirk said, we can't say more about this without more information on the function). 然后调用适当的函数以释放内存(如Dirk所说,如果没有更多有关该函数的信息,我们将无法对此进行更多介绍)。
If it really must be allocated before calling, it should be something looking like this: 如果确实必须在调用之前分配它,则它应该类似于以下内容:
[DllImport("yourfile.dll", CharSet = CharSet.Ansi)]
public static extern sbyte service_GetParameter ( String parameter, Int32 length, ref IntPtr val);
public static string ServiceGetParameter(string parameter, int maxLength)
{
string ret = null;
IntPtr buf = Marshal.AllocCoTaskMem(maxLength+1);
try
{
Marshal.WriteByte(buf, maxLength, 0); //Ensure there will be a null byte after call
IntPtr buf2 = buf;
service_GetParameter(parameter, maxLength, ref buf2);
System.Diagnostics.Debug.Assert(buf == buf2, "The C++ function modified the pointer, it wasn't supposed to do that!");
ret = Marshal.PtrToStringAnsi(buf);
}
finally { Marshal.FreeCoTaskMem(buf); }
return ret;
}
I'd start with something like this: 我将从这样的事情开始:
[DllImport("yourfile.dll", CharSet = CharSet.Ansi]
public static extern Int32 service_GetParameter([MarshalAs(UnmanagedType.LPStr)] String szParameter, Int32 value_length, [Out] StringBuilder sbValue);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.