C#中调用VC编写的dll库
来源:互联网 发布:北京四达时代通讯网络 编辑:程序博客网 时间:2024/05/19 06:34
如何在C#中调用DLL(C/C++写的)。举一个我做过的例子说明:
建立VC工程DllDemo,建立的时候选择MFC AppWizard(dll),选择Regular Dll using shared MFC Dll或者MFC Extension Dll。
现在可以写一个函数代码,在DllDemo.cpp文件中添加这些代码。也可以使用新的文件添加代码;
- extern “C“ __declspec(dllexport) int Add(int a,int b)
- {
- AFX_MANAGE_STATE(AfxGetStaticModuleState());
- TRACE("Entering DllAdd\n");
- return a+b;
- }
编译工程。
下面建立一个C#的WinForm程序测试DllDemo:
启动vs.net IDE,建立新的C#工程,选择WinForm应用程序。
在Form1.cs中添加引用:using System.Runtime.InteropServices;
在pulic class Form1声明的开头添加代码:
- [DllImport("MotorControlDll.dll",EntryPoint="Add",
- ExactSpelling=false,CallingConvention=CallingConvention.Cdecl)]
- public static extern int Add(int a,int b);
至于DllImport属性的用法可以察看MSDN,对于各项参数有详细的说明。
最后还要记得将DllDemo生成的位于Debug文件中DllDemo.dll文件加入到C#的WinForm程序的bin目录下。
这样就可以直接使用Add(int a,int b)函数。
这样,就完成了C#中调用dll库。
//---------------------------------------------------
c#控制台程序:
1. C++ 部分:
// TestDll.cpp : Defines the exported functions for the DLL application.//#include "stdafx.h"extern "C" __declspec(dllexport) int GetReport(int id, char* retPath) { strcpy_s(retPath,1,""); return -1; }
2. C# 部分, Console项目。
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Runtime.InteropServices;namespace ConsoleApplication1{ class Program { [DllImportAttribute("TestDll.dll", EntryPoint = "GetReport", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)] public unsafe static extern int GetReport(int id, [MarshalAsAttribute(UnmanagedType.LPStr)] System.Text.StringBuilder retPath); static void Main(string[] args) { int x = Program.GetReport(3, new StringBuilder("askask")); Console.WriteLine(x.ToString()); } }}
运行C#项目后,得到正确的返回值 -1.
- 在C#中调用VC编写的dll库
- 在C#中调用VC编写的dll库
- 在C#中调用VC编写的dll库
- C#中调用VC编写的dll库
- C#中调用dll库(VC编写)
- MFC中调用C#编写的DLL
- C#中调用C++编写的Dll
- Java中调用C#编写的dll
- VC DLL的编写调用
- C#2005调用VC编写的DLL时出错
- 在vb,vc中调用vb编写的DLL
- Delphi中调用VC编写的DLL内对象
- 如何在VB中调用VC编写的DLL
- 在vb,vc中调用vb编写的DLL
- 在VC中调用BCB编写的标准DLL函数库
- 【C#语法】C#中调用C++编写的dll
- VC调用C#的DLL
- C# 中调用 C++编写的 dll 的 调试
- PowerDesigner15.1汉化+注册补丁
- ZooKeeper 典型的应用场景
- CountDownLatch简述
- HDU 2037 - 今年暑假不AC(贪心 + 动态)
- c/c++static
- C#中调用VC编写的dll库
- java读取properties文件方法和对比
- Android入门之Service和BroadcastReceiver
- Timus 1057 数位dp
- dom4j xml解析
- 大数相乘
- 新的开始 new start
- QML数据模型(Model)
- Epoch时间和可读时间的相互转换