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 <stdio.h>
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 < len; ++i) {
sum += arr[i];
}
return sum;
}
void ChangeContent(double* arr, int len)
{
for (int i = 0; i < len; ++i) {
arr[i] += 1;
}
}
void FillStudents(Student* students, int len)
{
for (int i = 0; i < len; ++i) {
char* name = "Tom";
memcpy(students[i].name, name, strlen(name));
students[i].gender = i % 2;
students[i].mark = i * 10;
}
}
C#调用平台相关方法基础
参看微软的dotnet文档,使用System.Runtime.InterpoServices
命名空间中的DllImport
注解引入现有的动态链接库中的函数方法进行调用。下文将对常用的几种函数原型调用方法进行演示
调用无参数方法
调用无参数方法非常简单,声明一个静态外部方法,添加注解即可
[DllImport("dll_demo.dll", EntryPoint = "Foo", CallingConvention = CallingConvention.Cdecl)]
public static extern void Foo();
调用多个参数并返回值的案例
CLR类型的多个参数方法只需要正常定义即可,如实现一个加法
[DllImport("dll_demo.dll", EntryPoint = "Add", CallingConvention = CallingConvention.Cdecl)]
public static extern int Add(int a, int b);
调用指针参数的案例
如果要对一个数组进行累加怎么办呢,我们可以发现其实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上的讨论对这个问题有详细的解释
说明
如果看不到控制台输出需要在工程中把项目类型改成控制台程序