//extern "C" CP_API int __stdcall   char* GetValueStr(const char* propertyName);
        [DllImport("ZSDK.dll", CharSet = CharSet.Ansi)]
        public static extern string GetValueStr(string propertyName);
在xp下运行正常,在win7系统下使用提示“尝试读取或写入受保护的内存。这通常指示其他内存已损坏”是不是我的声明有问题,还请高人解答?

解决方案 »

  1.   

    http://topic.csdn.net/u/20090522/20/ae470ef3-b964-4c45-aa89-4b07ae7b4ef6.html
      

  2.   

    我修了声明没有异常了,但是返回值是空值,是不是还是声明的问题呢?        //extern "C" CP_API int __stdcall   char* GetValueStr(const char* propertyName);
            [DllImport("ZSDK.dll",CharSet=CharSet.Ansi)]
            [return: MarshalAs(UnmanagedType.BStr)]
            public static extern string GetValueStr([MarshalAs(UnmanagedType.BStr)]string propertyName);
      

  3.   

    dll与语言没有关系的。只要引用进来调用可以了。
      

  4.   

    跟语言没关系,但是跟你怎么写的有关系。你可以仔细学习一下这片文档,我估计你的问题就是由于CLR试图释放你的字符串指针两遍而导致的。
    http://msdn.microsoft.com/en-us/library/f1cf4kkz(VS.80).aspxHowever, if you define the method as a platform invoke prototype, replace each BSTR type with a String type, and call MethodOne, the common language runtime attempts to free b twice. You can change the marshaling behavior by using IntPtr types rather than String types.
      

  5.   


    [DllImport("ZSDK.dll",CharSet=CharSet.Ansi)]
      public static extern IntPtr GetValueStr([MarshalAs(UnmanagedType.BStr)]string propertyName);IntPtr buff=GetValueStr("");
    string s=Marshal.PtrToStringBSTR(buff);你需要确定C++中用的是否是BStr类型,如不是可以尝试PtrToStringAnsi ,PtrToStringAuto PtrToStringUni http://msdn.microsoft.com/zh-cn/library/system.runtime.interopservices.marshal_methods(v=VS.80).aspx  
      

  6.   

    很显明 char * = UnmanagedType.LPStr
      

  7.   

    这个函数写得不好
    应该以参数形式返回
    GetValueStr(const char* propertyName, char *buff, int buffLength);
    这样可以由调用方控制内存的申请和释放,避免内存泄露
      

  8.   

     [DllImport("ZSDK.dll",CharSet=CharSet.Ansi)]
      [return: MarshalAs(UnmanagedType.BStr)]
      public static extern string GetValueStr([MarshalAs(UnmanagedType.BStr)]string propertyName);我也遇到过类似的问题,不知道解决办法是否相同。我当时是用一个返回bool类型的DLL函数,也是出现返回值不正确的问题,但后来加上了 [return: MarshalAs(UnmanagedType.I1)]后就没问题了,所以我认为你可能是在  [return: MarshalAs(UnmanagedType.BStr)]这句上有问题,看看string是否应该对应UnmanagedType.BStr这种类型。