从C#传递字符串到C DLL

6
我正在尝试将一个字符串从C#传递到C DLL。根据我所读的,.NET应该为我执行从字符串到char*的转换,但是我得到了“error CS1503:Argument'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);
}

1
为什么要将StreamReceiveInitialise声明为不安全的?现在你仍然需要传递char*而不是字符串。 - diggingforfire
我现在已经移除了不安全的代码,并使用答案1中展示的代码。 - integra753
3个回答

3

将你的外部方法声明为:

public static extern bool StreamReceiveInitialise(string filepath);

1

使用 StringBuilder 代替 char*。请参见this

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

1

像这样做:

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

(将Marshalling作为UnmanagedType.LPStr是默认值,但我喜欢明确说明)。


1
那个[MarshalAs]属性是不必要的,因为在这种情况下字符串已经是默认的封送方式。 - Hans Passant
1
但在DllImport属性上指定CharSet不是一个坏主意。 - Ben Voigt
我应该提到我不需要在C代码中修改文件路径。这会改变你的评论吗?抱歉,我对混合C/C#还很新。 - integra753
CharSet.ANSI 是默认值,但我同意应该明确指定。 - Rasmus Faber
我已经指定了CharSet.ANSI。 - integra753

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接