C#调用C++中dll

花开花折 2017-09-28 04:47:06
C++ 中函数及结构体
函数名: FontRecord* GetAllFontRecord(int& nFontNum );
Struct FontRecord
{
TCHAR szFontName[256];
DWORD dwFontAttrib;
}

C#中结构体定义
IntPtr GetAllFontRecord(out nFontNum );
[StructLayout(LayoutKind.Sequential),CharSet=CharSet.Unicode]
public struct PassOutput
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string[] szFontName;
public int dwFontAttrib;
}

3:函数调用
FontRecord fontRecord=new FontRecord ();
FontRecord fontRecord1=new FontRecord ();
fontRecord.szFontName=new string[256];

IntPtr indata = IntPtr.Zero;
IntPtr outdata = IntPtr.Zero;
Marshal.StructureToPtr(fontRecord, indata, false);
outdata = GetAllFontRecord(out nFontNum);
fontRecord1=(FontRecord )Marshal.PtrToStructure(outdata, typeof(FontRecord ));

现运行到 Marshal.StructureToPtr(fontRecord, indata, false)提示值不能为null;




...全文
168 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
xian_wwq 2017-09-29
  • 打赏
  • 举报
回复
1. 建议把c++的方法再封装一层,转为纯C的接口,这样问题少一点 2. 对于结构体的操作,参考这样,其中,TagAttr是个自定义结构体

int size = Marshal.SizeOf(typedef(TagAttr)) ;  
IntPtr attrInput = Mashal.AllocHGlobal(count*size);  
DBPT.GetTagsAttributeWithPtr(nHandle,count,out errors,ids, attrInput);  
for(int i = 0;i< count;i++)  
{  
    IntPtr ptr = (IntPtr)((UInt32)attrInput + i* size);  
    tagsArray[i] = (TagAttr)Mashal.PtrToStructure(ptr,typeof(TagAttr));  
}  
Marshal.FreeHGlobal(attrInput); 
xian_wwq 2017-09-29
  • 打赏
  • 举报
回复
有一处定义不对

   [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
    public string[] szFontName;
不能用string[],char[]数组对应的string
真相重于对错 2017-09-29
  • 打赏
  • 举报
回复
出现错误,请查msdn public static void StructureToPtr( Object structure, IntPtr ptr, bool fDeleteOld ) ptr 类型: System .IntPtr 指向非托管内存块的指针,必须在调用此方法之前分配该指针。
Acme_Thanatos 2017-09-29
  • 打赏
  • 举报
回复
//创建byte数组 byte[] _bytes = new byte[size]; 、、 上面 这句不需要...
Acme_Thanatos 2017-09-29
  • 打赏
  • 举报
回复
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct PassOutput
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
    public string szFontName;
    public int dwFontAttrib;
}

//得到结构体的大小
int size = Marshal.SizeOf(fontRecord);
//创建byte数组
byte[] _bytes = new byte[size];
//分配结构体大小的内存空间
IntPtr indata  = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(fontRecord, indata, false);

110,533

社区成员

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

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

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