如题,在C#里调用C++ dll,在xp,2003下都测试无问题,在win7 32位版调用失败(提示,是很常见的那个内存错误或内存保护之类的)C#编译时是any cpu,DLL编译时是win32平台DLL代码(刚学C++,不是太懂),生成名字是StrUtils.dll:#include <string>
using namespace std;extern "C" _declspec(dllexport) char* _stdcall getKeyValue(int);
extern "C" _declspec(dllexport) void _stdcall freeResult();
char* resultVal;
char* _stdcall getKeyValue(int type)
        {
            string FROM_STRING = "b8z(9&hk7x8wH$";
            string FROM_STRING1="y2BI0q5QF8m4T5";
            string resultStr="xxxxx";
            if(type==1)
                resultStr=FROM_STRING+FROM_STRING1;
            int len=resultStr.length();
    resultVal=new char[len+1];
    strcpy(resultVal,resultStr.c_str());
    resultVal[len]='\0';
    return resultVal;
        }void _stdcall freeResult()
{
if(resultVal!=NULL)
delete[] resultVal;
}C#调用代码[DllImport("StrUtils.dll", CharSet = CharSet.Ansi)]
private static extern string getKeyValue(int y);[DllImport("StrUtils.dll", CharSet = CharSet.Ansi)]
private static extern void freeResult();  //释放内存 static void Main(string[] args)
        {
          string q = getKeyValue(1);
          freeResult();
          Console.writeLine(q);
          Console.ReadKey();
        }            
MSDN丛书中,说C# string 对应 C++中 char*,应该数据转换没错啊但这样在win7中运行不了根据网上资料,修改为这样时才可用[DllImport("StrUtils.dll", CharSet = CharSet.Ansi)]
private static extern IntPtr getKeyValue(int y);[DllImport("StrUtils.dll", CharSet = CharSet.Ansi)]
private static extern void freeResult();  //释放内存 static void Main(string[] args)
        {
          IntPtr q = getKeyValue(1);
          string r=Marshal.PtrToStringAnsi(q);
          freeResult();
          Console.writeLine(r);
          Console.ReadKey();
        }
哪们高人指点下,原因在哪??

解决方案 »

  1.   

    你在C#里调用getKeyValue(1);传的1
    strcpy(resultVal,resultStr.c_str());内存已经越界 
      

  2.   

    1、调用函数时加上变量加上ref试试[DllImport("StrUtils.dll", CharSet = CharSet.Ansi)]
    private static extern IntPtr getKeyValue(ref int y);
    2、参数类型可能不对,数据类型不对,你把C++的Dll改成long型,然后在用C#调用试试仅供参考,一般出现你的错误都是数据类型的事