CSharp如何调用dll中带指针参数Word文档格式.docx
- 文档编号:16094271
- 上传时间:2022-11-19
- 格式:DOCX
- 页数:7
- 大小:15.11KB
CSharp如何调用dll中带指针参数Word文档格式.docx
《CSharp如何调用dll中带指针参数Word文档格式.docx》由会员分享,可在线阅读,更多相关《CSharp如何调用dll中带指针参数Word文档格式.docx(7页珍藏版)》请在冰豆网上搜索。
publicstaticexternvoidfun(Int32value);
publicstaticexternvoidfun(floatvalue);
publicstaticexternvoidfun(charch);
2.参数为基本类型+指针,例如int*,float*,char*等
voidfun(int*value);
voidfun(float*vaue);
voidfun(char*ch);
publicstaticexternvoidfun(refInt32value);
publicstaticexternvoidfun(reffloatvalue);
参数为char*,在C#中有几种实现方式
A.publicstaticexternvoidfun(stringch);
//ch内容不会改变
B.publicstaticexternvoidfun(StringBuilderch);
//ch内容会改变
3.参数为结构体
structpoint
{
intvalue;
//基本类型
charch;
intnumber[100];
//数组
charbuffer[100];
//字符串数组
};
voidfun(pointpt);
[StructLayout(LayoutKind.Sequential)]
publicstructpoint
publicInt32value;
publiccharch;
[MarshalAs(UnmanagedType.ByValArray,SizeConst=100)]
publicInt32[]number;
[MarshalAs(UnmanagedType.ByValTStr,SizeConst=100)]
publicchar[]buffer;
}
publicstaticexternvoidfun(pointpt);
4.参数为结构体指针
voidfun(point*pt);
publicstaticexternvoidfun(refpointpt);
5.参数为结构体,并且结构体还嵌套结构体
structpointpt;
//嵌套结构体
publicpointpt;
6.参数为结构体,并且结构体还嵌套结构体指针或者双指针
structpoint*p1;
//嵌套结构体指针
structpoint**p2;
//嵌套结构体双指针
publicIntPtrp1;
//使用IntPtr替代嵌套指针
publicIntPtrp2;
由于嵌套指针的使用比较复杂,需要借助一些手段才能够确保正常调用DLL方法
classProgram
[StructLayout(LayoutKind.Sequential)]
publicstructpoint
{
publicInt32value;
publiccharch;
[MarshalAs(UnmanagedType.ByValArray,SizeConst=100)]
publicInt32[]number;
[MarshalAs(UnmanagedType.ByValTStr,SizeConst=100)]
publicchar[]buffer;
publicIntPtrp1;
publicIntPtrp2;
}
[DllImport("
publicstaticexternvoidfun(pointpt);
staticvoidMain(string[]args)
pointpt=newpoint();
pt.p1=Marshal.AllocHGlobal(Marshal.Sizeof(typeof(point)));
pt.p2=Marshal.AllocHGlobal((Marshal.SizeOf(typeof(point)))*2);
try
{
pt.value=1;
//实现给p1赋值
pointptt=newpoint();
ptt.value=1;
Marshal.StructureToPtr(ptt,pt.p1,false);
//实现给p2赋值
//由于双指针不能够直接传值,需要用到中间结构的数组指针
IntPtr[]ptr=newIntPtr[2];
ptr[0]=Marshal.AllocHGlobal(Marshal.SizeOf(typeof(point)));
ptr[1]=Marshal.AllocHGlobal(Marshal.SizeOf(typeof(point)));
try
{
Marshal.StructureToPtr(ptt,ptr[0],false);
Marshal.Copy(ptr,0,pt.p2,2);
fun(pt);
//测试返回的指针值是否正确
ptt=(point)Marshal.PtrToStructure(pt.p1,typeof(point));
Marshal.Copy(pt.p2,ptr,0,2);
ptt=(point)Marshal.PtrToStructure(ptr[0],typeof(point));
ptt=(point)Marshal.PtrToStructure(ptr[1],typeof(point));
}
catch(System.Exceptione)
stringstr=e.Message;
finally
Marshal.FreeHGlobal(ptr[0]);
Marshal.FreeHGlobal(ptr[1]);
}
catch(System.Exceptione)
stringstr=e.Message;
finally
Marshal.FreeHGlobal(pt.p1);
Marshal.FreeHGlobal(pt.p2);
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- CSharp 如何 调用 dll 指针 参数