1

我在 c# 中工作,我需要从 c++ dll 使用这个函数:

extern "C" char   IMPEXP __stdcall service_GetParameter ( const char* parameter, const int value_lenght, char** value );

我在 C++ 代码中使用它如下:

char *val = new char[256];
service_GetParameter("firmware_version", 255, &val);
AnsiString FirmwareVersion = val;
delete[] val;

如何导入此函数并在 c# 中使用它?

提前致谢

4

2 回答 2

2

如果此函数分配内存并让调用者负责释放它,恐怕您将不得不手动管理:将参数声明为 aref IntPtr并使用Marshal类的方法获取带有指向数据副本的 String .

然后调用适当的函数来释放内存(正如 Dirk 所说,如果没有关于该函数的更多信息,我们无法对此进行更多说明)。

如果它真的必须在调用之前分配,它应该是这样的:

[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;
}
于 2013-05-31T13:00:23.910 回答
1

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);
于 2013-05-31T12:29:31.137 回答