2013-08-20 108 views
0

我有一个问题,试图导入C++ DLL到C#尝试读取或写入受保护的内存 - dllimport的

我总是得到错误“试图读取或写入保护内存”当我打电话的构造该dll类。我一直在其他解决方案中锁定相同的答案,但我找不到解决方案。

我决定用一个简单的函数丢弃来自C++部分附带的错误,但我有同样的问题...

这里是我的代码:

的main.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 
} 

main.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(); 
     } 
    } 
} 

我生气了,这不是那么难。

在此先感谢。

+1

你确定你必须像你的函数/方法一样对待你的构造函数吗?你并没有在'simple_dll'构造函数上使用'new',毕竟... –

+0

是的,那也是。如果你想真正构造,你需要使用对象大小的AllocCoTaskMem(),然后*调用它的构造函数...更容易导出一个静态方法,它执行'new'(和另一个一个是静态的,不是'删除')。 – Medinoc

+0

我遵循这个例子:http://social.msdn.microsoft.com/Forums/vstudio/en-US/0ad74be1-8152-4bb4-8ced-3a400c04182d/dll-import-in-c也许不是rigth要做的事 –

回答

0

问题是调用约定。在当前表单中,功能导出为thiscall,但DllImport属性默认为stdcall(或智能手机上的cdecl)。

+0

我应该如何解决这个问题?我已经改变了你在[dllimport]调用惯例,但结果是一样的... –

+1

我不确定。我从来没有导出本地C++类(更不用说跨越语言界限),只有函数和COM接口... – Medinoc

相关问题