尝试使用c#中使用c ++构建的dll文件中的函数;下面是c ++ .h代码
#pragma once
#pragma unmanaged
#ifndef _DLL_H_
#define _DLL_H_
#if BUILDING_DLL
# define DLLIMPORT __declspec (dllexport)
#else /* Not BUILDING_DLL */
# define DLLIMPORT __declspec (dllimport)
#endif /* Not BUILDING_DLL */
#include <list>
#include <string>
using namespace std;
extern "C"
{
string DLLIMPORT encrypt(string keeper);
string DLLIMPORT decrypt(string keeper);
}
#endif /* _DLL_H_ */
c ++ .cpp代码在
之下#pragma managed
#include "cenH.h"
#include <windows.h>
#include <iostream>
using namespace std;
const char alphabets[] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n',
'o','p','q','r','s','t','u','v','w','x','y','z'};
string encrypt(string keeper)
{
string keep;
string m = keeper;
cout << keeper.length() << endl;
for(int count = 0; count < m.length(); count++)
{
for(int c = 0; c < 26; c++)
{
if(m[count] == alphabets[c])
{
int counter = c - 8;
if(counter < 0)
{
counter = counter + 26;
keep += alphabets[counter];
}
else
{
keep += alphabets[counter];
}
}
else if(m[count] == ' ')
{
keep+=".";
break;
}
}//end of second loop
//end first loop
cout << keep << endl;
return keep;
}
string decrypt(string keeper)
{
//cout << "\n" << endl;
string keep;
string m = keeper;
for(int count = 0; count < m.length(); count++)
{
for(int c = 0; c < 26; c++)
{
if(m[count] == alphabets[c])
{
int counter = c + 8;
if(counter >= 26)
{
counter = counter - 26;
keep += alphabets[counter];
}
else
{
keep += alphabets[counter];
}
}else if(m[count] == '.')
{
keep+=" ";
break;
}
}//end of third loop
}//end second loop
//cout << keep << endl;
return keep;
}
BOOL APIENTRY DllMain (HINSTANCE hInst /* Library instance handle. */ ,
DWORD reason /* Reason this function is being called. */ ,
LPVOID reserved /* Not used. */ )
{
switch (reason)
{
case DLL_PROCESS_ATTACH:
break;
case DLL_PROCESS_DETACH:
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
}
/* Returns TRUE on success, FALSE on failure */
return TRUE;
}
我编译这些代码,他们不会给出错误,我甚至通过调用dll文件测试在c ++控制台应用程序中运行它们并且它工作正常但是当我将这个dll文件调用到我的c#程序时它给了我AccessViolationException尝试到读或写受保护的内存。这通常表明其他内存已损坏。 dll在MinGW GCC 4.6.2 32位中编译,我的c#在x86(32位)上运行。有人请指出我做错了什么。
这是我在c#code
中导入dll的方法[DllImport("cen.dll",CallingConvention = CallingConvention.StdCall)]
internal static extern string decrypt(String keeper);
string line = decrypt("savethemonkeys");