如何使用C#调用C dll? [英] how to use C# invoke C dll?

查看:77
本文介绍了如何使用C#调用C dll?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C code







// The cJSON structure:
typedef struct cJSON {
struct cJSON *next,*prev;
struct cJSON *child;
int type; // The type of the item, as above.

char *valuestring; // The item's string, if type==cJSON_String
int valueint; // The item's number, if type==cJSON_Number
double valuedouble; // The item's number, if type==cJSON_Number

char *string; // The item's name string, if this item is the child of, or is in the list of subitems of an object.
} cJSON;

typedef struct cJSON_Hooks {
  void *(*malloc_fn)(size_t sz);
  void (*free_fn)(void *ptr);
} cJSON_Hooks;

// Supply malloc, realloc and free functions to cJSON
__declspec(dllexport) void cJSON_InitHooks(cJSON_Hooks* hooks);











C# code



命名空间DeviceApplication1
{
公共局部类Form1:Form
{
公共Form1()
{
InitializeComponent();
}

[DllImport("cJson.dll")]
公共静态外部无效cJSON_InitHooks(cJSON_Hooks *挂钩);
}
}


cJSON_Hooks和cJSON是cJson.h中的结构,但是在C#代码中,cJSON_Hooks和cJSON无法被识别.如果有人可以引导我通过或指出正确的方向,将不胜感激.谢谢



namespace DeviceApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

[DllImport("cJson.dll")]
public static extern void cJSON_InitHooks(cJSON_Hooks* hooks);
}
}


cJSON_Hooks and cJSON is a struct in cJson.h, but in C# code ,cJSON_Hooks and cJSON can''t be incognizanced. If someone could walk me through it or point me in the right direction it would be greatly appreciated. Thanks

推荐答案

,您还需要在C#中创建与其布局相同的结构,以便您可以将其传递.www.pinvoke. net有很多例子.
you need to also create a struct that is the same in it''s layout, in C#, so you can pass it in. www.pinvoke.net has lots of examples how this is done.


谢谢!但是,我不知道如何重写"struct cJSON * next,* prev; struct cJSON * child;"
谁能帮助我将此结构覆盖到C#中?非常感谢!!!!
thanks!but, I don''t konw how to overwirte "struct cJSON *next,*prev;struct cJSON *child;"
who can help me overwirte this struct to C#? thanks very much!!!


在这种情况下,我不会采用针刺的方式...使用C ++/CLI创建一个托管的ref类,该类​​引用并管理了以下代码的生命周期这些cJSON对象,并公开适当的方法和属性来查询它们.这些将对任何.NET程序都是可见的.然后,在您的C#程序中,仅使用此CLR类.
I wouldn''t do it the pinvoke way in this case... Use C++/CLI to create a managed ref class which references and manages the lifetime of those cJSON objects and exposes appropriate methods and properties to query them. These will be visible to any .NET program. Then, in your C# program use only this CLR class.


这篇关于如何使用C#调用C dll?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆