【问题标题】:Pass string from C# to C DLL将字符串从 C# 传递到 C DLL
【发布时间】:2012-02-12 08:09:21
【问题描述】:

我正在尝试将字符串从 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);
}

【问题讨论】:

  • 为什么将 StreamReceiveInitialise 声明为不安全?现在你仍然需要传递一个 char* 而不是一个字符串。
  • 我现在已经删除了 unsafe 并且正在使用,如答案 1 所示。

标签: c# c string dll char


【解决方案1】:

将您的外部方法声明为:

public static extern bool StreamReceiveInitialise(string filepath);

【讨论】:

    【解决方案2】:

    这样做:

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

    (编组为 UnmanagedType.LPStr 是默认设置,但我喜欢明确)。

    【讨论】:

    • 那个 [MarshalAs] 属性是不必要的,在这种情况下它已经是字符串的默认编组。
    • 但是在DllImport 属性上指定CharSet 并不是一个坏主意。
    • 我应该提到我不需要在 C 代码中修改文件路径。这会改变你的cmets吗?抱歉,我是混合 C/C# 的新手。
    • CharSet.ANSI 是默认的,但我同意它应该被指定为明确的。
    • 我已经指定了 CharSet.ANSI。
    【解决方案3】:

    使用 StringBuilder 代替 char*。见this

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

    【讨论】:

      猜你喜欢
      • 2014-02-24
      • 1970-01-01
      • 1970-01-01
      • 2011-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多