试图读取或写入受保护的内存 - dllimport

时间:2013-08-20 12:23:30

标签: c# c++ unmanaged

我在尝试将c ++ dll导入c#

时遇到问题

当我调用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 个答案:

答案 0 :(得分:0)

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