在C#中调用C语言标准动态库方法

在C#中调用C语言标准动态库方法

1.打造标准动态库
__declspec(dllexp ort) int __cdecl add(int, int);//这一句是声明动态库输出一个可供外不调用的函数原型.
int add(int a,int b) {//实现这个函数
return a+b;
}
以上基本 3行代码,声明一个add的要领 , 输入参数是两个int参数,返回这两个数之和. 保存为MyLib.c
然后执行编译命令.
H:\XSchool\C#-School\HowTo>cl /LD MyLib.c
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 12.00.8168 for 80×86
Copyright (C) Microsoft Corp 1984-1998.  All rights reserved.

MyLib.c
Microsoft (R) Incremental Linker Version 6.00.8447
Copyright (C) Microsoft Corp 1992-1998. All rights reserved.

/out:MyLib.dll
/dll
/implib:MyLib.lib
MyLib.obj
Creating library MyLib.lib and object MyLib.exp

确信有以上输出, 说明编译成功生成了动态库.

2.编写C-Sharp程序调用该动态库
using System;
using System.Runtime.InteropServices;//这是用到DllImport时候要引入的包

public class InvokeDll {
[DllImport("MyLib.dll", CharSet=CharSet.Auto)]
static extern int add(int a,int b);//声明外部的标准动态库, 跟Win32API是一样的.

public static void Main() {
Console.WriteLine(add(10,30));
}
}
保存为InvokeDll.cs文件, 与MyLib.dll置于同一目录, 编译该文件.
H:\XSchool\C#-School\HowTo>csc invokedll.cs
将生成Invokedll.exe, 可以执行该文件.

另付:

C#调用C函数的方法:

方法一:

1.新建Visual C++类型的Win32项目
C语言的函数定义如下:
extern “C” __declspec(dllexport) int fnTestWin32(void);
实现如下
extern “C” __declspec(dllexport) int fnTestWin32(void)
{
return 42;
}
工程属性页[常规]->[配置类型]选择[动态库.dll]
会生成.lib和.dll文件。用Dependency工具能看到fnTestWin32函数,因为使用了extern “C”

2.C#工程中
[DllImport("TestWin32.dll", EntryPoint = "fnTestWin32", CharSet = CharSet.Ansi)]
private static extern int fnTestWin32();
把Win32项目生成的dll拷贝到C#生成的exe文件,就可以调用了。

方法二:

1.新建Win32工程
直接使用C语言,函数定义不使用extern “C” __declspec(dllexport)
工程属性页[常规]->[配置类型]选择[静态库(.lib)]

2.新建Visual C++ CLR 类库工程
这里面写的是C++的类,提供给C#直接调用的,作为C与C#的中转,主要使用Marshal类
应用上面的Win32工程,并包含头文件
extern “C”
{
#include “app_notify.h”
}

原创文章,转载请注明: 转载自Seth's Blog by hekai

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值