C # calls functions in an unmanaged dynamic library

Source: Internet
Author: User
Tags reserved

How C # calls a function in an unmanaged dynamic library, such as a dynamic library written with VC6, the process of C # calling a dynamic library is much faster than a Java call DLL dynamic Library, as illustrated in the following example.

1. Create an unmanaged dynamic library

The code is as follows:

extern  "C" __declspec(dllexport) int add( int , int );
int add( int a, int b)

Note that the above code, must add extern "C", can not be generated in the dynamic library of the exported function name is not add, but like? add@ @YAHHH @z appearance, followed by the function name add to locate functions of the portal will be problematic.

Save as a C or CPP file, and then use command cl (This command VC6 provides) to compile a dynamic library, which commands the following:

C:>cl /LD MyLib.cpp
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 12.00.8804 for 80x86
Copyright (C) Microsoft Corp 1984-1998. All rights reserved.
Microsoft (R) Incremental Linker Version 6.00.8447
Copyright (C) Microsoft Corp 1992-1998. All rights reserved.
Creating library MyLib.lib and object MyLib.exp

You can see in the C-packing directory generated you want the dynamic library MyLib.Dll, but also accompanied by the generation of MyLib.lib, Mylib.obj, mylib.exp files, the above command CL parameter/LD is to generate dynamic library files

2. Write C # program call Dynamic Library

using System;
using System.Runtime.InteropServices; //这是用到DllImport时候要引入的包
public  class InvokeDll{
[DllImport( "MyLib.dll" , CharSet=CharSet.Auto)]  
staticexternint add( int a, int b); //声明外部的标准动态库, 跟Win32API是一样.
public  static  void Main()

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.