2013-08-20 107 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

相關問題