读书人

C#调用MFC DLL 接口返回值类型是char

发布时间: 2013-01-01 14:04:19 作者: rapoo

C#调用MFC DLL 接口返回值类型是char * 但内容是乱码
C#调用MFC DLL 接口返回值类型是char * 但内容是乱码,经过测试在接口返回之前使用AfxMessageBox弹出指针,内容是正确的,但是到c#程序里面弹出的时候就全部变成了乱码。请各位同行帮忙分析一下。不胜感激!
[解决办法]
注意字符串编码

[解决办法]
是不是在dll里空间被释放了
这个dll是你自己写的么
[解决办法]
注意数据类型。

c#没有char 这个概念。 要转换数据类型的话, System.Runtime.InteropServices.Marshal 类

,看看这个代码吧:


using namespace System;
using namespace System::Runtime::InteropServices;

public value struct Point
{
public:
property int X;
property int Y;
};
extern bool CloseHandle(IntPtr h);

int main()
{
// Demonstrate the use of public static fields of the Marshal
// class.
Console::WriteLine(
"SystemDefaultCharSize={0},SystemMaxDBCSCharSize={1}",
Marshal::SystemDefaultCharSize,
Marshal::SystemMaxDBCSCharSize);

// Demonstrate the use of the SizeOf method of the Marshal
// class.
Console::WriteLine("Number of bytes needed by a Point object: {0}",
Marshal::SizeOf(Point::typeid));
Point point;
Console::WriteLine("Number of bytes needed by a Point object: {0}",
Marshal::SizeOf(point));

// Demonstrate how to call GlobalAlloc and
// GlobalFree using the Marshal class.
IntPtr hglobal = Marshal::AllocHGlobal(100);
Marshal::FreeHGlobal(hglobal);

// Demonstrate how to use the Marshal class to get the Win32
// error code when a Win32 method fails.
bool isCloseHandleSuccess = CloseHandle(IntPtr(-1));
if (!isCloseHandleSuccess)
{
Console::WriteLine(
"CloseHandle call failed with an error code of: {0}",
Marshal::GetLastWin32Error());
}
};

// This is a platform invoke prototype. SetLastError is true,
// which allows the GetLastWin32Error method of the Marshal class
// to work correctly.
[DllImport("Kernel32", ExactSpelling = true, SetLastError = true)]
extern bool CloseHandle(IntPtr h);

// This code produces the following output.
//
// SystemDefaultCharSize=2, SystemMaxDBCSCharSize=1


// Number of bytes needed by a Point object: 8
// Number of bytes needed by a Point object: 8
// CloseHandle call failed with an error code of: 6


[解决办法]
呃应该是mfc 的dll 返回了局部变量的地址了。
改为使用参数传递字符串吧。
[解决办法]
引用:
引用:

注意数据类型。

c#没有char 这个概念。 要转换数据类型的话, System.Runtime.InteropServices.Marshal 类

,看看这个代码吧:

C/C++ code

using namespace System;
using namespace System::Runtime::Inter……

那就是返回局部变量了
[解决办法]
引用:
引用:

呃应该是mfc 的dll 返回了局部变量的地址了。
改为使用参数传递字符串吧。


可以更详细点吗?

这样的代码就不行。成功与否完全看 人品值。
char* func()
{
char sz[]="aaaab";
return sz;
}

[解决办法]
char 里面存的如果是 'A', 显示的可能会是 65, 请转换一下呀.

读书人网 >VC/MFC

热点推荐