我正在尝试将字符串从C#传递给C DLL。从我所读到的.NET应该为我做从字符串到char *的转换,但是我得到"错误CS1503:参数' 1':不能转换为'字符串' to' 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);
}
答案 0 :(得分:3)
将您的外部方法声明为:
public static extern bool StreamReceiveInitialise(string filepath);
答案 1 :(得分:1)
这样做:
[DllImport("Source.dll", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.ANSI)]
static extern bool StreamReceiveInitialise([MarshalAs(UnmanagedType.LPStr)] string filepath);
(编组为UnmanagedType.LPStr是默认值,但我喜欢显式)。
答案 2 :(得分:1)
使用StringBuilder代替char *。见this
[DllImport("Source.dll")]
public static extern bool StreamReceiveInitialise(StringBuilder filepath);