c语言如何做成.dll的东西?然后用c#做界面调用这个c程序?

c语言如何做成.dll的东西?然后用c#做界面调用这个c程序?

下边那位太懒了吧,从其他地方copy的都不改一些?
我自己写了一种方法,你看看是不是你要的,过程如下:
新建空的解决方案 -- 添加项目--VC++--Win32项目 -- 输入名字点确认 -- 向导里选下一步 -- 将应用程序类型改为Dll,然后点完成就可以了,在你的源文件cpp里写函数就可以了,写法示例:extern "C" __declspec(dllexport) int add(int x, int y)
{
return x+y;
}

然后生成,在debug里找到dll文件(最好把dll,lib,pdb都copy过来),copy到你的C#的bin文件夹下
在C#里添加一个cs函数,在里面添加引用using System.Runtime.InteropServices;
class 前添加public(改成public才可以被其他调用)
在class里添加C里面函数的声明;示例如下
[DllImport("text.meo.dll")]
public static extern int add(int x,int y);
然后在其他地方就可以通过这个cs函数.add调用add函数,其他的函数和这一样操作

我这边测试是没什么问题,有什么疑问再问我
温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-09-11
写动态库:
/*
* libsthcpp.h
* Declarations for function cppadd //声明函数cppadd
*/
#include "stdio.h"
#include "stdlib.h"
#include "stdarg.h" //stdandard argument(标准参数),用的都是c的头文件,方便以后c调用?
#ifdef __cplusplus //参考我之前的文章
extern "C"
{
#endif

int cppadd(int x, int y); //不用类来写c++!没有参考性,凑合看了
#ifdef __cplusplus
}
#endif

/*
* libsthcpp.cpp
* Implementation of function cppadd declared in libsthcpp.h//实现函数
* in c++ language
*/
#include "libsthcpp.h"
//和之前说的不同,前面说的使用externa "C"关键字,对于c++被c调用的,cpp文件中,也要写上去。
int cppadd(int x, int y)
{
return x + y;
}
C#调用DLL
使用C#时不免用调用别的DLL,如WIN32的API和自己以前做的DLL,包括不同语言之间的的dll
C#调用DLL很像VB,下面讨论的C#调用DLL的方式。
看看下面的例子,演示了怎么定义DLL函数接口
public class Utility
{
[DllImport("kernel32",
EntryPoint="CreateDirectory",
CallingConvention=CallingConvention.StdCall)]
public static extern bool Create (string name);

[DllImport("User32",
EntryPoint="MessageBox",
CallingConvention=CallingConvention.StdCall)]
public static extern int MsgBox (string msg);
}

class MyClass
{
public static int Main()
{
string myString;
Console.Write("Enter your message: ");
myString = Console.ReadLine();
return Utility.MsgBox(myString);
}
}

值得注意的是,缺省的调用规则(CallingConvention)是Stdcall,同Winapi,在
C++里是__stdcall的形式,函数入口(EntryPoint)缺省是同名,如CreateDirectory
的定义也可以为
[DllImport("kernel32")]
static extern bool CreateDirectory(string name, SecurityAttributes sa);

WIN32 API原型为
BOOL CreateDirectory(
LPCTSTR lpPathName, // directory name
LPSECURITY_ATTRIBUTES lpSecurityAttributes // SD
);
相似回答