将参数从 C# 传递到C++ Dll 并返回的正确方法是什么?
What is the correct way to pass arguments to a C++ Dll from C# and back?
我正在研究一个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上表现不同?
提前感谢!
根据问题中的信息,您的代码是正确的。问题可能出在其他地方。显而易见的地方是非托管代码。我建议你调试一下。
您的代码是等待发生的缓冲区溢出。如果被调用方不知道缓冲区的大小,如何避免缓冲区溢出?选项包括:
- 将缓冲区长度传递给非托管代码。 使用
- 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# 应用程序调用。
相关文章:
- 从父类方法返回子类对象
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 让bool方法返回其他整数
- 不能将方法返回的值用于另一个方法
- 如何实现 Front() 方法以返回模板化双向链表C++的第一个元素?
- 从私有成员变量的成员方法返回unique_ptr
- 我的模板类方法返回错误类型?
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- QtQuick - qml:28:错误:未知方法返回类型:自定义类型
- 方法错误"not all control paths return a value"和方法不返回值
- GRPC C++ TLS 客户端 grpc::SslCredentials() 方法不返回
- 我无法使用C++指针指向类方法返回的 std::vector
- 如何在工厂方法中返回指向基于基础操作系统的派生类的有效指针
- 将传入的网络"char*"数据转换为"uint8_t"并返回的安全方法是什么?
- C++方法是否可以根据传递给构造函数的参数具有不同的返回类型?
- EnQueue 方法在循环队列中未正确返回C++?
- 应用于const和非const对象的引用返回方法
- 在vc++ PPL中,如何创建一个同步返回的任务返回方法
- 为什么从浮点返回方法返回双精度不会在 c++ 中导致任何错误/警告
- 这个返回方法叫什么?