从c#调用c++ DLL和访问冲突问题,我的选择是什么
calling c++ dll from c# and accessviolation issue, what are my choices?
我有一个64位的c++ DLL,我没有代码。我有。h和。lib对应的文件。
我可以毫无问题地调用2个api。它们返回版本号。所以这告诉我DLL在我的应用程序中正确加载,一切都很好。
有问题的API接受const char *:
bool func(const char *a, const char *b, const char *c, const char *d, const char *e, int number);
我已经创建了一个c#包装器:
[DllImport(mDllName, CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)]
private static extern bool func(string a,
string b,
string c,
string d,
string e,
int number);
我知道这个包装器是可以的,因为参数是文件名。如果我传入一个不存在的文件名,我得到一个从DLL生成的对话框,说文件名不存在。然而,这个函数崩溃了,"访问冲突读取位置0x3C"。
所以我的看法是我写的c#包装器没有问题。我知道c++ dll工作正常,因为我正试图将现有的工作c++应用程序转换为c#。c++应用程序已经使用了有问题的DLL。
那么这里可能发生了什么?我的看法是,也许在实际的DLL中有一个错误,但问题并不严重到足以在c++应用程序中呈现,因为也许内存没有像c#应用程序那样严格检查?
如果是这种情况,是否有任何设置我可以关闭检查内存不那么严格的c#?或者我的选择是什么,考虑到我没有也永远不会访问DLL的源代码。
进一步分析:我创建了一个简单的WIN32 64位DLL,它有这些api:
__declspec(dllexport) char *hello()
{
return "Hello from DLL !";
}
__declspec(dllexport) int number()
{
return 1979;
}
我有c#包装器如下:
[DllImport("MAFuncWrapper.dll", CharSet=CharSet.Ansi)]
public static extern string hello();
[DllImport("MAFuncWrapper.dll")]
public static extern int number();
我可以成功地调用number(),但试图调用hello()给我:
First-chance exception at 0x00000000774B4102 (ntdll.dll) in WindowsFormsApplication1.exe: 0xC0000374: A heap has been corrupted (parameters: 0x000000007752B4B0).
If there is a handler for this exception, the program may be safely continued.
p/invoke看起来很好,对应该封送为UnmanagedType.U1
的返回值取模。
没有神奇的开关可以用来抑制这个错误。你必须解决这个问题。
如果你有一个c++程序在调用函数时成功,而你的c#程序失败了,那么c#程序似乎在某些方面有所不同。消除差异来解决问题。
关于你在编辑中问的另一个问题,这是错误的:
[DllImport("MAFuncWrapper.dll", CharSet=CharSet.Ansi)]
public static extern string hello();
string
返回值导致编组程序调用返回指针上的CoTaskMemFree
。因此产生了错误。
您必须声明返回类型为IntPtr
并将其传递给Marshal.PtrToStringAnsi
。
- 我的神经网络不起作用 [XOR 问题]
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 代码在我的计算机上运行良好,但是在将其提交给coursera时遇到未知的信号11问题
- 为我的 c++ 类介绍制作一个三角形分类器.我有几个问题
- 我的逻辑反转字符串中的元音有什么问题?
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 我的超类中的模板问题与结构定义
- N-queen问题:无法弄清楚为什么我的解决方案不起作用
- 我的问题是关于C++中数字和序列的重复以及如何打印它们?
- 在我的四叉树实现中遇到问题
- 我的C++语言蛮力算法有问题
- C++无法解决我的问题。我有控制台错误
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- 我应该在 main 函数中写什么来测试我的问题?
- 任何人都可以告诉我我的 C++ 代码出了什么问题?
- 我的堆栈和库存清单程序的结构有什么问题?
- 我在使用 boost::serialization 时遇到了一个问题,我的代码在 Linux 中运行良好,但在 Wind
- 什么是非营利组织???我的问题是我不明白为什么有人会使用它
- 为什么我的程序在打开网络设备时遇到问题
- C++ 回文程序总是给出 0(假)作为输出问题;我的代码哪里有问题?