C#DllImport和封送处理char ** [英] C# DllImport and Marshaling char**

查看:417
本文介绍了C#DllImport和封送处理char **的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working in c# and I need to use this function from a c++ dll:

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

我已在c ++代码中使用它,如下所示:

I have used it in c++ code as follow:

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

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

How can I import this function and use it in c#?

预先感谢

推荐答案

如果此函数分配了内存并使调用者负责释放它,我将恐怕您将不得不手动进行管理:将参数声明为 ref IntPtr 并使用 Marshal

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.

然后调用适当的函数来释放内存(正如Dirk所说,我们不能多说

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).

如果确实必须在调用之前分配它,它应该看起来像这样:

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;
}

这篇关于C#DllImport和封送处理char **的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆