一、DllImportAttribute

1、属性介绍

 using System;
using System.Reflection;
using System.Security; namespace System.Runtime.InteropServices
{
// Summary:
// Indicates that the attributed method is exposed by an unmanaged dynamic-link
// library (DLL) as a static entry point.
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
[ComVisible(true)]
public sealed class DllImportAttribute : Attribute
{
// Summary:
// Enables or disables best-fit mapping behavior when converting Unicode characters
// to ANSI characters.
public bool BestFitMapping;
//
// Summary:
// Indicates the calling convention of an entry point.
public CallingConvention CallingConvention;
//
// Summary:
// Indicates how to marshal string parameters to the method and controls name
// mangling.
public CharSet CharSet;
//
// Summary:
// Indicates the name or ordinal of the DLL entry point to be called.
public string EntryPoint;
//
// Summary:
// Controls whether the System.Runtime.InteropServices.DllImportAttribute.CharSet
// field causes the common language runtime to search an unmanaged DLL for entry-point
// names other than the one specified.
public bool ExactSpelling;
//
// Summary:
// Indicates whether unmanaged methods that have HRESULT or retval return values
// are directly translated or whether HRESULT or retval return values are automatically
// converted to exceptions.
public bool PreserveSig;
//
// Summary:
// Indicates whether the callee calls the SetLastError Win32 API function before
// returning from the attributed method.
public bool SetLastError;
//
// Summary:
// Enables or disables the throwing of an exception on an unmappable Unicode
// character that is converted to an ANSI "?" character.
public bool ThrowOnUnmappableChar; // Summary:
// Initializes a new instance of the System.Runtime.InteropServices.DllImportAttribute
// class with the name of the DLL containing the method to import.
//
// Parameters:
// dllName:
// The name of the DLL that contains the unmanaged method. This can include
// an assembly display name, if the DLL is included in an assembly.
public DllImportAttribute(string dllName); // Summary:
// Gets the name of the DLL file that contains the entry point.
//
// Returns:
// The name of the DLL file that contains the entry point.
public string Value { get; }
}
}

2、举例

 class BLApi
{
[DllImport(@"xx.dll", EntryPoint = "TWelcomeFace_Init", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)]
public extern static Int32 TWelcomeFace_Init(string namingService, string localhost, string dvsService, string matchService);
}

3、引入依赖dll

将依赖dll添加到解决方案中,与主dll放在相同目录下(重要),然后设置dll的属性CopyToOutputDirectory= CopyAlways,编译器就会自动找到了。

二、应用LoadLibrary

1、封装基础类

 public class DllInvoke
{
[DllImport("kernel32.dll")]
private extern static IntPtr LoadLibrary(String path);
[DllImport("kernel32.dll")]
private extern static IntPtr GetProcAddress(IntPtr lib, String funcName);
[DllImport("kernel32.dll")]
private extern static bool FreeLibrary(IntPtr lib);
[DllImport("kernel32.dll")]
private extern static int GetLastError();
private IntPtr hLib;
public DllInvoke(String dllPath, List<string> DependentDllPaths = null)
{
if(DependentDllPaths != null)
{
foreach (string dllName in DependentDllPaths)
{
IntPtr loadAuxiliary = LoadLibrary(dllName);
if (loadAuxiliary == IntPtr.Zero)
{
throw new Exception(dllName + "加载失败!");
}
}
}
hLib = LoadLibrary(dllPath);
}
~DllInvoke()
{
FreeLibrary(hLib);
} public Delegate Invoke(String APIName, Type t)
{
IntPtr api = GetProcAddress(hLib, APIName);
var s = Marshal.GetDelegateForFunctionPointer(api, t);
return (Delegate)s;
}
}

LoadLibrary引用的dll相关的依赖dll必须被手动引用进来,否则会报错。

2、举例

 [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi, SetLastError = true)]
delegate Int32 TWelcomeFace_Init(string Naming_Service, string Locale_Host, string DVS_Service, string Match_Service); class BLApi
{
private static DllInvoke _dll = new DllInvoke(@"xx.dll"); public static Int32 TWelcomeFace_Init(string namingService, string localhost, string dvsService, string matchService)
{
try
{
TWelcomeFace_Init dele = (TWelcomeFace_Init)_dll.Invoke("TWelcomeFace_Init", typeof(TWelcomeFace_Init));
Int32 result = dele(namingService, localhost, dvsService, matchService); return result;
}
catch (Exception ex)
{
throw ex;
}
}
}

[原创]C#引用C++编译的dll的更多相关文章

  1. 关于.Net中Process的使用方法和各种用途汇总(二):用Process启动cmd.exe完成将cs编译成dll

    上一章博客我为大家介绍了Process类的所有基本使用方法,这一章博客我来为大家做一个小扩展,来熟悉一下Process类的实际使用,废话不多说我们开始演示. 先看看我们的软件要设计成的布局吧. 首先我 ...

  2. Unity插件之Unity调用C#编译的DLL

    Unity插件分为两种:托管插件(Managed Plugins)和本地插件(Native Plugins).本文先来说说Unity中的托管插件,本地插件的文章留到下一篇文章再说. 有时候我们会有这样 ...

  3. Unity 代码编译成dll 更新dll实现热更代码

    Unity 代码编译成dll 更新dll实现热更代码 实现流程 代码编译成DLL DLL打包成AssetBundle 加载AssetBundle 加载代码程序集 获取指定类 使用反射赋值 C#代码编译 ...

  4. 如何使用g++编译调用dll的c++代码

    本文将有以下4个部分来讲如何使用g++编译调用dll的c++代码. 1.如何调用dll 2.动态链接和静态链接的区别 3.g++的编译参数以及如何编译调用dll的c++代码 4.总结 1.如何调用dl ...

  5. C#.NET常见问题(FAQ)-如何将cs文件编译成dll文件 exe文件 如何调用dll文件

    比如我要把TestDLL.cs文件编译成dll文件,则在命令提示符下,输入下面的命令,生成的文件为TestDLL.dll csc /target:library TestDLL.cs 注意前提是你安装 ...

  6. 使用RazorGenerator和预编译MVC引擎将Razor视图编译成DLL

    Web开发中常常会有跨页面.跨站点.跨项目组的复用模块(界面),最常见的就是如下方所示的Web页面上用于显示登录或用户名的头部模块, 使用ASP.NET MVC开发中,常见的做法是写成部分视图,本文的 ...

  7. Golang 编译成 DLL 文件

    golang 编译 dll 过程中需要用到 gcc,所以先安装 MinGW. windows 64 位系统应下载 MinGW 的 64 位版本: https://sourceforge.net/pro ...

  8. asp.net源程序编译为dll文件并调用的实现过程

    很多时候,我们需要将.cs文件单独编译成.dll文件,这就需要使用csc命令将.cs文件编译成.dll动态链接库文件.具体的操作步骤如下: 打开命令窗口->输入cmd到控制台->cd C: ...

  9. VC将同一份代码同时编译为Dll和Exe的方法

    开发中经常遇到这样的情况,需要开发一个某某功能的接口Dll,但是Dll不能直接调试,你至少需要一个Loader 但是Loader和Dll本身不在同一个工程里,虽然都在本机的话并不影响源码级调试,但是总 ...

随机推荐

  1. Pro Git 第一章 起步 读书笔记

    Pro Git 笔记 第1章 起步 1.文件的三种状态. 已提交:文件已经保存在本地数据库中了.(commit) 已修改:修改了某个文件,但还没有提交保存.(vim) 已暂存:已经把已修改的文件放在下 ...

  2. 2016-2017 ACM-ICPC, NEERC, Southern Subregional Contest (Online Mirror) in codeforces(codeforces730)

    A.Toda 2 思路:可以有二分来得到最后的数值,然后每次排序去掉最大的两个,或者3个(奇数时). /************************************************ ...

  3. 在AngularJS中同一个页面配置一个或者多个ng-app

    在AngularJS学习中,对于ng-app初始化一个AngularJS程序属性的使用需要注意,在一个页面中AngularJS自动加载第一个ng-app,其他ng-app会忽略, 如果需要加载其他ng ...

  4. android shortcut &livefoulder

    android shortcut(实现步骤) 1.建立activity 2.minifest 里面注册并加上intent-filter,name为:android.intent.action.CREA ...

  5. js跨域访问,No 'Access-Control-Allow-Origin' header is present on the requested resource

    js跨域访问提示错误:XMLHttpRequest cannot load http://...... No 'Access-Control-Allow-Origin' header is prese ...

  6. VBS整人代码

    记得刚开始学VB脚本语言的时候,写了一段调用系统进程的代码,挺好的: dim wshif msgbox("笑笑很帅",vbyesno,"请回答是或否")=vby ...

  7. 蚁群算法简介(part3: 蚁群算法之更新信息素)

    信息素的局部更新策略   每只蚂蚁在构造出一条从起点到终点的路径后,蚁群算法还要求根据路径的总长度来更新这条路径所包含的每条边上信息素的浓度(在旅行商问题中每座城市是图中的一个节点,城市两两间有一条边 ...

  8. sort排序

    /*问题 L: 使用sort排序题目描述标准库的sort函数给我们提供了一个很方便的排序的方法,光听别人说方便不顶事,得自己亲自实践一下才能体会到它的方便之处. 输入每组包含多组数据,每组数据第一行包 ...

  9. Java的数据类型

    在JAVA中一共有八种基本数据类型,他们分别是byte.short.int.long.float.double.char.boolean整型其中byte.short.int.long都是表示整数的,只 ...

  10. django例子,question_text为中文时候报错

    问题描述 UnicodeEncodeError at /admin/polls/question/3/ 'ascii' codec can't encode characters in positio ...