我在尝试将 c++ dll 导入 c# 时遇到问题
当我调用 dll 类的构造函数时,我总是收到错误“试图读取或写入受保护的内存”。我一直在锁定其他解决方案以获得相同的答案,但我找不到解决方案。
我决定使用一个简单的函数来丢弃错误来自 c++ 部分,但我遇到了同样的问题......
这是我的代码:
主.cpp:
#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__
和 C# 代码:
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();
}
}
}
我生气了,这不可能这么难。
提前致谢。