简体   繁体   English

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

[英]Pass string from C# to C DLL

I am trying to pass a string from C# to a C DLL. 我试图将字符串从C#传递给C DLL。 From what I have read .NET should do the conversion from string to char* for me, however I get "error CS1503: Argument '1': cannot convert from 'string' to 'char*'" Can someone advise me of where I have went wrong? 从我读到的.NET应该为我做从字符串到char *的转换,但是我得到“错误CS1503:参数'1':无法从'字符串'转换为'字符*'”有人可以告诉我我在哪里出了什么问题? Thanks. 谢谢。

C# code 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 C DLL

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

将外部方法声明为:

public static extern bool StreamReceiveInitialise(string filepath);

Do it like this: 像这样做:

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

(Marshalling as UnmanagedType.LPStr is the default, but I like being explicit). (编组为UnmanagedType.LPStr是默认值,但我喜欢显式)。

Use a StringBuilder in place of char*. 使用StringBuilder代替char *。 See this 看到这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM