高分求救 懂C# 调用C++Dll的请进,

shilei831115 2012-05-25 09:31:00
C++ 调用Dll的方法如下:

void CCallDllDlg::Find()
{
int cx,cy;//找到图片的横坐标cx和纵坐标cy
CString temp_x,temp_y;//
CString msg="Pee_Shangx.bmp";//要查找的bmp文件(24位色位图)
HINSTANCE hDllInst = LoadLibrary("FindPic.dll");

if(hDllInst)
{

typedef void (*MYFUNC)(CString,int*,int*);

MYFUNC youFuntionNameAlias = NULL; // youFuntionNameAlias 函数别名

youFuntionNameAlias = (MYFUNC)GetProcAddress(hDllInst,"FindPic");
// youFuntionName 在DLL中声明的函数名

if(youFuntionNameAlias)
{
youFuntionNameAlias(msg,&cx,&cy);

temp_x.Format("%d",cx);
temp_y.Format("%d",cy);
AfxMessageBox("横坐标"+temp_x+" 纵坐标"+temp_y);
SetCursorPos(cx,cy);//移动鼠标到图片位置
}
FreeLibrary(hDllInst);
}



下面是C# 调用的代码

private int iHwnd = 0; //DLL句柄
private delegate void FindPictures(StringBuilder strFileName, ref int iX, ref int iY);
private FindPictures fp;
private const string DLLNAEM = "FindPic.dll";


[DllImport("kernel32.dll", EntryPoint = "LoadLibrary", SetLastError = true)]
public static extern IntPtr LoadLibrary(string lpFileName);

[DllImport("kernel32.dll", EntryPoint = "GetProcAddress", SetLastError = true)]
public static extern IntPtr GetProcAddress(IntPtr hModule, string lpProceName);

[DllImport("kernel32.dll", EntryPoint = "FreeLibrary", SetLastError = true)]
public static extern bool FreeLibrary(IntPtr hModule);


public static Delegate GetAddress(IntPtr dllModule, string functionname, Type t)
{
IntPtr addr = GetProcAddress(dllModule, functionname);
if (addr == IntPtr.Zero)
return null;
else
return Marshal.GetDelegateForFunctionPointer(addr, t);

}


public void FindPicFunction(StringBuilder strName, ref int iX, ref int iY)
{
try
{
ipt = LoadLibrary(DLLNAEM);
if (ipt == IntPtr.Zero)
return;
fp = (FindPictures)GetAddress(ipt, "FindPic", typeof(FindPictures));
fp(strName, ref iX, ref iY);//这里就提示出错.说类型错误.//------------------------------------
}
catch
{
//出错
}
finally
{
FreeLibrary(ipt);
}
}





到标记的地方出错.错误代码如下

对 PInvoke 函数“#!#.Control.FindPicClass+FindPictures::Invoke”的调用导致堆栈不对称。原因可能是托管的 PInvoke 签名与非托管的目标签名不匹配。请检查 PInvoke 签名的调用约定和参数与非托管的目标签名是否匹配。


问题: 请问这个CString 到底应该和C# 的那种类型相对应.? (String是尝试过了.不行 StringBuilder也不行.
)
...全文
204 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
风之影子 2012-05-27
  • 打赏
  • 举报
回复
http://www.dreamdu.com/blog/2008/04/25/cs_cpp_functionpointer/
bdmh 2012-05-26
  • 打赏
  • 举报
回复
CString是mfc的,c#用不了,如果你不能修改dll,就不要用了,想起他办法
WAN 2012-05-26
  • 打赏
  • 举报
回复
根据这里的error,可以在声明private delegate void FindPictures...前加上[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
这样这个error可能不会出现,或者变成其它error,但CString的问题仍然未解决

CString是MFC专门定义的字符串操作类,要使用,则要求MFC支持。如果dll要跨语言调用,则通常不应使用这些特定语言的特定类型。
C#支持的平台调用字符串类型一般是以'\0'结尾的C类型字符串,没有任何的已有C#类型能和CString对应,在C#中直接使用CString几乎是不可能的。
最靠谱的两种解决方法,要么修改这个FindPic.dll,把CString改为LPCTSTR等方式,要么要再写一个带MFC支持的dll,封装FindPic函数,间接的调用它

111,096

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧