您的位置:首页 > 新闻动态 > Unity3D

UNITY3D C#调用C封装的函数库方法

来源: 2023/10/30      点击:

如果在C函数库test.dll中存在函数int test1(int a, int b), 那么C#对动态库函数的引用可以这样声明,之后可以调用test1函数.

[DllImport("test", EntryPoint = "test1", CallingConvention = CallingConvention.Cdecl)]
public static extern int test1(int a, int b);
那么如果函数是指针参数怎么办? 

若dll中存在函数int test2(int *a, int *b), 那么C#对动态库函数的引用可以这样声明,之后可以调用test2函数.

[DllImport("test", EntryPoint = "test1", CallingConvention = CallingConvention.Cdecl)]
public static extern int test1(ref int a,ref int b);
如遇到函数的参数为结构体又该如何呢? 
struct mydatapack
{
    string name;
    string sex;
    int age;
}
int test3(struct mydatapack data);

我们可以这样声明:

[StructLayout(LayoutKind.Sequential)] 
public struct datapaclk 
{ 
    public string name; 
    public string sex;
    public string age; 
    public datapack(string Name,string Sex, int age) 
    { 
        this.name= Name; 
        this.sex= Sex;
        this.age = Age; 
    } 
} 
[DllImport("test", EntryPoint = "test3", CallingConvention = CallingConvention.Cdecl)] 
public static extern int test3(datapack data);