将字符串从C#传递到C DLL

本文关键字:DLL 字符串 | 更新日期: 2023-09-27 18:20:45

我正试图将一个字符串从C#传递到一个C DLL。根据我所读到的内容,.NET应该为我完成从字符串到char*的转换,但我得到了"错误CS1503:参数'1':无法从'string'转换为'char*'"。有人能告诉我哪里出了问题吗?谢谢

C#代码

[DllImport("Source.dll", ExactSpelling = true, CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
public static unsafe extern bool StreamReceiveInitialise(char* filepath);
const string test = "test";
// This method that will be called when the thread is started
public void Stream()
{
    if (StreamReceiveInitialise(test))
    {

    }
}

C DLL

extern "C"
{
    __declspec(dllexport) bool __cdecl StreamReceiveInitialise(char* filepath);
}

将字符串从C#传递到C DLL

将外部方法声明为:

public static extern bool StreamReceiveInitialise(string filepath);

使用StringBuilder代替char*。查看此

[DllImport("Source.dll")]
public static extern bool StreamReceiveInitialise(StringBuilder filepath);

这样做:

[DllImport("Source.dll", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.ANSI)]
static extern bool StreamReceiveInitialise([MarshalAs(UnmanagedType.LPStr)] string filepath);

(默认情况下封送为UnmanagedType.LPStr,但我喜欢显式)。