ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

从C#传递字符串到c dll

2019-07-04 01:52:13  阅读:199  来源: 互联网

标签:c pinvoke dll dllimport intptr


我在c#应用程序中使用c dll时遇到了一些麻烦.给我一个错误的函数在dll的头文件中定义,如下所示:

int __stdcall DDC_CreateFilePropertyString (DDCFileHandle file, 
                                        const char *property,
                                        const char *value);

我在我的类中添加了以下代码,我访问了dll.

[DllImport("nilibddc.dll", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)]
private static extern int DDC_CreateFilePropertyString(IntPtr file,
                         [MarshalAs(UnmanagedType.LPStr)]string property,
                         [MarshalAs(UnmanagedType.LPStr)]string value);

类型DDCFileHandle在头文件中定义如下:

typedef struct _DDCFile DDCFile;
typedef DDCFile*    DDCFileHandle;

在头文件中没有关于_DDCFile结构的其他信息(我没有使用库中的任何其他文件).

在我调用函数DDC_CreateFilePropertyString()之前,我调用以下函数来创建文件并获取文件句柄.

[DllImport("nilibddc.dll", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi]
private static extern int DDC_CreateFile(char[] filePath,
                          char[] fileType,
                          char[] name,
                          char[] description,
                          char[] title,
                          char[] author,
                          ref IntPtr file);

头文件中的定义如下所示.

int __stdcall DDC_CreateFile (const char *filePath,
                          const char *fileType,
                          const char *name,
                          const char *description,
                          const char *title,
                          const char *author,
                          DDCFileHandle *file);

现在总是当我调用函数DDC_CreateFilePropertyString时,它返回一个错误,告诉我传递了一些错误的参数.我究竟做错了什么?我正在使用的库是National instruments的TDMS C API.

谢谢你的帮助.

解决方法:

你的p / invokes有点偏.您需要使用CallingConvention.Stdcall,这是默认设置.对于const char *参数,您应该简单地将它们声明为C#end处的字符串.

DDC_CreateFile的正确C#p / invoke是:

[DllImport("nilibddc.dll", CharSet=CharSet.Ansi]
private static extern int DDC_CreateFile(
    string filePath,
    string fileType,
    string name,
    string description,
    string title,
    string author,
    ref IntPtr file
);

对于DDC_CreateFilePropertyString,您需要这样:

[DllImport("nilibddc.dll", CharSet=CharSet.Ansi)]
private static extern int DDC_CreateFilePropertyString(
    IntPtr file,
    string property,
    string value
);

如果在修复代码后,在调用这些函数时仍然会收到错误,那么您显然是错误地使用了库.这超出了这个问题的范围.查阅文档,和/或寻求图书馆供应商的支持.

标签:c,pinvoke,dll,dllimport,intptr
来源: https://codeday.me/bug/20190704/1372522.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有