Simple WPF: C#调用C/C++动态链接库中的函数 您所在的位置:网站首页 python调用c动态库 Simple WPF: C#调用C/C++动态链接库中的函数

Simple WPF: C#调用C/C++动态链接库中的函数

2023-03-14 22:14| 来源: 网络整理| 查看: 265

C#调用原生 C/C++的方法本文记录了如何从.NET下调用原生的C语言编译生成的动态链接库函数。 文中介绍了以下几种调用无参无返回方法 有参有返回方法 指针参数方法 结构体指针参数方法 代码可以从以下仓库找到,希望可以帮到有需要的人 Github: https://github.com/mrchipset/simple-wpf实验用到的C语言动态链接库源码// foo.h #pragma once typedef struct _Student { char name[32]; int gender; int mark; } Student; __declspec(dllexport) void Foo(); __declspec(dllexport) int Add(int x, int y); __declspec(dllexport) double Sum(const double* arr, int len); __declspec(dllexport) void ChangeContent(double* arr, int len); __declspec(dllexport) void FillStudents(Student* students, int len);

// foo.c #include "foo.h" #include void Foo() { printf("Hello World!\n"); } int Add(int x, int y) { return x + y; } double Sum(const double* arr, int len) { double sum = 0.0; for (int i = 0; i 调用指针参数的案例

如果要对一个数组进行累加怎么办呢,我们可以发现其实C语言中的数组类型是一个指针,通过制定数组首地址和元素个数可以实现累加。

在C#中声明函数原型传入内存首地址和个数即可

[DllImport("dll_demo.dll", EntryPoint = "Sum", CallingConvention = CallingConvention.Cdecl)] public static extern double Sum(double[] arr, int n);

如果想要改变传入指针指向的内容怎么做呢,其实对于CLR类型和上面的累加操作的定义是一模一样的

[DllImport("dll_demo.dll", EntryPoint = "ChangeContent", CallingConvention = CallingConvention.Cdecl)] public static extern double Change(double[] arr, int n); 调用结构体参数的案例

对于调用结构体参数的函数首先要解决两个问题

C#怎么知道这个结构体的定义?C#中和C中的结构体内存是如何对齐的?

第两个问题相对也好解决,在C#代码中定义一个对应结构体,并规定结构体的内存排布方式。使用StructLayout注解进行限定内存排布顺序,使用MarshalAs注解规定一个特定的内存序列化方式

[StructLayout(LayoutKind.Sequential)] struct Student { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] public byte[] name; public int gender; public int mark; }

对于函数的声明有所不同,如果在原生代码中需要修改结构体的内容,需要对要修改的参数添加[Out]注解,否则无法成功修改

[DllImport("dll_demo.dll", EntryPoint = "FillStudents", CallingConvention = CallingConvention.Cdecl)] public static extern void FillStudents([In, Out] Student[] students, int len);

StackOverflow上的讨论对这个问题有详细的解释

说明

如果看不到控制台输出需要在工程中把项目类型改成控制台程序

参考P/INVOKE的微软文档c# wpf 通过控制台打印输出的两种方法C# 调用 C++ DLL方法Passing an struct array into C++ DLL from C#C#调用C++数组,结构体DLL



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

      专题文章
        CopyRight 2018-2019 实验室设备网 版权所有