本文调用的类库是上一遍博文中,自己封装的一个类库demo例程,
博文地址:https://blog.youkuaiyun.com/wangMaryann/article/details/105665917
类库代码地址:https://download.youkuaiyun.com/download/wangMaryann/12348492
c#开发平台:vs2017
1、类库中共封装了连个函数,首先需要将函数载入进来
class CDll
{
[DllImport("hdll.dll", EntryPoint = "add", CallingConvention = CallingConvention.StdCall)]
private static extern unsafe bool add(int a, int b, ref int sum);
public bool myAdd(int a, int b, ref int sum)
{
return add(a, b,ref sum);
}
[DllImport("hdll.dll", EntryPoint = "sub", CallingConvention = CallingConvention.StdCall)]
private static extern unsafe bool sub(ref int sub, int a, int b);
public bool mySub(ref int result, int a, int b)
{
return sub(ref result, a, b);
}
}
注意:在 [DllImport("hdll.dll", EntryPoint = "add", CallingConvention = CallingConvention.StdCall)] 中,EntryPoint的函数名称,可以通过dll库查看软件(Depends.exe),查看具体的函数名称,注意写法要一致,否则可能载入失败。
2、函数载入进来以后,就可调用使用了,代码如下
try
{
CDll cdll = new CDll();
int a = 10;
int b = 5;
int sum = 0;
int result = 0;
bool b1 = cdll.myAdd(a,b,ref sum);
bool b2 = cdll.mySub(ref result, a, b);
}
catch (Exception ex)
{
string str = ex.ToString();
throw;
}
博文中c#代码地址:
https://download.youkuaiyun.com/download/wangMaryann/12350616