将参数从 C# 传递到C++ Dll 并返回的正确方法是什么?

本文关键字:返回 方法 是什么 Dll 参数 C++ | 更新日期: 2023-09-27 18:31:23

我正在研究一个C++DLL,它应该能够接收一些参数并将其传递回C#应用程序。

我能够做到这一点,这工作正常。至少我是这么认为的。代码在我的电脑上运行良好,但在我同事的电脑上无法正常工作。在他的 PC 上,相同的代码(在我的 PC 上没有错误地工作)产生不相同的输出,或者产生错误。所以基本上它的行为非常奇怪。

C++功能:

extern "C"
{
   __declspec( dllexport ) BOOL __stdcall MyFunction( char * StringIn, char *StringOut, BOOL bState );
}

我在 C# 中以这种方式使用它:

    [DllImport( @"PathToMyDll.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall )]
    public static extern bool MyFunction( string StringToDLL, StringBuilder StringFromDLL, bool bState );
    static void Main(string[] args)
    {
        int bufferSize = 16384;
        string StringToDLL = "This is a sample string";
        StringBuilder StringFromDLL = new StringBuilder( bufferSize );
        Console.WriteLine( "Return value      = " + MyFunction( StringToDLL, StringFromDLL, true ).ToString() );
        Console.WriteLine( "Sent to DLL       = " + StringToDLL.ToString() );
        Console.WriteLine( "Returned from DLL = " + StringFromDLL.ToString() );
        Console.ReadLine();
    }

所以我的问题是:
我做错了什么吗?或者Visual Studio中是否有一些设置可能导致这种行为?另外,我应该如何正确分配 C# 中的 StringOut 内存?有一种情况是 StringOut 会比缓冲区大小大,但我不知道它到底有多大?(我只会在 DLL 中知道它)有没有人知道为什么相同的代码在不同的PC上表现不同?

提前感谢!

将参数从 C# 传递到C++ Dll 并返回的正确方法是什么?

根据问题中的信息,您的代码是正确的。问题可能出在其他地方。显而易见的地方是非托管代码。我建议你调试一下。

您的代码是等待发生的缓冲区溢出。如果被调用方不知道缓冲区的大小,如何避免缓冲区溢出?选项包括:

  1. 将缓冲区长度传递给非托管代码。
  2. 使用
  3. BSTR,它允许通过分配共享 COM 堆来使用任意长的字符串。

如果这有帮助,这就是我将基于 C++ 的 DLL 连接到 C# 的方式。

[DllImport("MyDLL.DLL", CharSet=CharSet.Ansi,ExactSpelling=true, 
           CallingConvention=CallingConvention.StdCall)]
public static extern int MyFunction 
(MarshalAs(UnmanagedType.LPTStr)]StringBuilder strinIn, 
[MarshalAs(UnmanagedType.LPStr)]StringBuilder stringOut);

所以区别在于我指定了元帅类型。

然后,C++ DLL(导出为"C"函数)将具有以下原型:

LONG WINAPI MyFunction(const char *In, char *Out);

注意:我不是 C# 专家。 这就是我需要做的,以使我的 C++ DLL 函数由 C# 应用程序调用。