c# 调用C++ API

cshape_gis 2010-01-19 06:40:21
我使用 DLLImport引用 c++api,, 要调用 int LClientRcv(char *data) 我写成 public externa static int LClientRcv(string pBuffer);;; C#调用后得不到值 。。请问如何解决
...全文
267 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
麦田追风 2010-01-19
  • 打赏
  • 举报
回复
传字符串是可以的

最好是有C++源码,一步一步跟进去,看问题出在哪
有些C++生产的dll字符集设置问题也会引起这种现象
RFEZGC 2010-01-19
  • 打赏
  • 举报
回复
char *data 按理来说就是string ,如果不行就换成intptr试试
qqiuzaihui 2010-01-19
  • 打赏
  • 举报
回复
[Quote=引用楼主 cshape_gis 的回复:]
我使用 DLLImport引用 c++api,,  要调用 int  LClientRcv(char *data)  我写成  public externa static int LClientRcv(string pBuffer);;; C#调用后得不到值 。。请问如何解决
[/Quote]
要用 ANSI 修饰, 类似于
[dllimport("your.dll"), Charset=ANSI]
的这种格式. 自己百度下.
Valefish 2010-01-19
  • 打赏
  • 举报
回复
mark
aofengdaxia 2010-01-19
  • 打赏
  • 举报
回复
记得使用stringbuilder,而不是string
hzsagile 2010-01-19
  • 打赏
  • 举报
回复
不好意思,更正申明中的错误

[DllImport("Kernel32.dll", EntryPoint = "GetVersionEx"]
private static extern bool GetVersionEx2(ref struct_OsVersionInformation pStruct_VersionInformation);
hzsagile 2010-01-19
  • 打赏
  • 举报
回复
参考,C#中调用WindowsAPI GetVersionEx()

//申明结构在内存中布局
[StructLayout(LayoutKind.Sequential)]
public struct struct_OsVersionInformation
{
public int dwOSVersionInfoSize;
public int dwMajorVersion;
public int dwMinorVersion;
public int dwBuildNumber;
public int dwPlatformID;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
//资料来源:学网(www.xue5.com),原文地址:http://www.xue5.com/itedu/200802/109538.html
public string szCSDVersion;
public ushort wServicePackMajor;
public ushort wServicePackMinor;
public ushort wSuiteMask;
public byte wProductType;
public byte wReserved;
}

//API函数调用申明
[DllImport("Kernel32.dll", EntryPoint = "GetVersionEx
private static extern bool GetVersionEx2(ref struct_OsVersionInformation pStruct_VersionInformation);

//注意ref 引用关键字
public static void GetOSVersion(ref struct_OsVersionInformation struct_osvi)
{
//建立结构实例
struct_osvi = new struct_OsVersionInformation();
//为新建的结构分配内存
struct_osvi.dwOSVersionInfoSize = Marshal.SizeOf(struct_osvi);
//结构引用
if (!GetVersionEx2(ref struct_osvi))
{
throw new Exception("GetVersionEx调用失败");
}

}
wuyq11 2010-01-19
  • 打赏
  • 举报
回复
C++ C#
char* string
传出的char* StringBuilder
short short
char byte
char[n] fixed byte[n]
结构指针 结构指针
函数指针 委托
结构体数组使用IntPtr
cshape_gis 2010-01-19
  • 打赏
  • 举报
回复
顶上来,急啊

110,545

社区成员

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

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

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