C# 试图读取或写入受保护内存-dllimport 我试图把一个C++ DLL导入到C<< /p>中,遇到了一个问题。
当我调用dll类的构造函数时,总是出现错误“试图读取或写入受保护内存”。我已经锁定了相同答案的其他解决方案,但我找不到解决方案 我决定用一个简单的函数来放弃这个错误来自C++部分,但是我也有同样的问题…… 这是我的密码: main.cpp:C# 试图读取或写入受保护内存-dllimport 我试图把一个C++ DLL导入到C<< /p>中,遇到了一个问题。,c#,c++,unmanaged,C#,C++,Unmanaged,当我调用dll类的构造函数时,总是出现错误“试图读取或写入受保护内存”。我已经锁定了相同答案的其他解决方案,但我找不到解决方案 我决定用一个简单的函数来放弃这个错误来自C++部分,但是我也有同样的问题…… 这是我的密码: main.cpp: #include "main.h" simple_dll::simple_dll(int num) : numero(num) {} int simple_dll::getNumero() { return this->numero; }
#include "main.h"
simple_dll::simple_dll(int num) : numero(num) {}
int simple_dll::getNumero() {
return this->numero;
}
extern "C" DLL_EXPORT BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
switch (fdwReason)
{
case DLL_PROCESS_ATTACH:
// attach to process
// return FALSE to fail DLL load
break;
case DLL_PROCESS_DETACH:
// detach from process
break;
case DLL_THREAD_ATTACH:
// attach to thread
break;
case DLL_THREAD_DETACH:
// detach from thread
break;
}
return TRUE; // succesful
}
主要条款h:
#ifndef __MAIN_H__
#define __MAIN_H__
#include <windows.h>
/* To use this exported function of dll, include this header
* in your project.
*/
#ifdef BUILD_DLL
#define DLL_EXPORT __declspec(dllexport)
#else
#define DLL_EXPORT __declspec(dllimport)
#endif
#ifdef __cplusplus
extern "C"
{
#endif
// void DLL_EXPORT SomeFunction(const LPCSTR sometext);
class DLL_EXPORT simple_dll {
public:
DLL_EXPORT simple_dll(int num);
DLL_EXPORT int getNumero();
int numero;
};
#ifdef __cplusplus
}
#endif
#endif // __MAIN_H__
我快发疯了,这不可能这么难
提前感谢。问题在于通话约定。在当前表单中,函数在
thiscall
中导出,但DllImport
属性默认为stdcall
(或智能手机上的cdecl
)。您确定必须将构造函数视为函数/方法吗?毕竟,您没有在simple\u dll
构造函数上使用new
,是的,也是这样。如果要真正构造,需要使用AllocTaskMem()和对象大小匹配,然后调用构造函数。。。更容易导出一个静态的方法来执行<代码>新的< /C> >(另一个,静态或不,这就是<代码>删除<代码> >。我遵循这个例子:也许不是调用C++类中的实例方法的严格的事情很难得到正确的,构造函数和析构函数以及对象大小是C++编译器的强大实现细节。使用G++当然不会使它更容易,C++编译器没有标准的ABI。只有静态方法才能很好地工作,例如,方法您应该用C++/CLI语言编写一个包装器。我应该如何解决这个问题?我在[dllimport]中将您的呼叫约定改为两者,但结果是一样的……我不确定。我从不导出本机C++类(更不用说跨越语言边界),只有函数和COM接口…
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Reflection;
namespace prueba_dll_VS
{
unsafe class Program
{
[System.Runtime.InteropServices.DllImport("simple_dll.dll", EntryPoint = "_ZN10simple_dllC2Ei")]
private static extern System.IntPtr simple_dll(int num);
[System.Runtime.InteropServices.DllImport("simple_dll.dll", EntryPoint = "_ZN10simple_dll9getNumeroEv")]
private static extern int getNumero(System.IntPtr hObject);
static void Main(string[] args)
{
System.IntPtr ptr_simple_dll = simple_dll(4); //HERE IS WHERE THE ERROR RAISES
int hora = getNumero(ptr_simple_dll);
Console.WriteLine(hora);
Console.ReadLine();
}
}
}