• C#如何调用C写的Win32 DLL


    1. 首先,在Visual Studio中,我们建立一个Visual C++的项目

        类型选择Win32 Project,继续选择Dll类型

        该项目取名叫做myDll

        1) 添加myDll.h头文件,代码如下:

    #ifdef A_EXPORTS
    #define DLL_API __declspec(dllexport)
    #else
    #define DLL_API __declspec(dllimport)
    #endif

    extern "C" DLL_API void HelloWorld();

        这里HelloWorld()就是等下我们要暴露给C#调用的C方法。

        注意:必须给函数增加extern "C"关键字,否则等下将无法找到该

                 函数的入口点。

      

        2)添加myDll.cpp文件,代码如下:

    #include "stdafx.h"
    #include 
    "myDll.h"

    #ifdef _MANAGED
    #pragma managed(push, off)
    #endif

    BOOL APIENTRY DllMain( HMODULE hModule,
                           DWORD  ul_reason_for_call,
                           LPVOID lpReserved
                         )
    {
        
    switch (ul_reason_for_call)
        {
            
    case DLL_PROCESS_ATTACH:
            
    case DLL_THREAD_ATTACH:
            
    case DLL_THREAD_DETACH:
            
    case DLL_PROCESS_DETACH:
            
    break;
        }

        
    return TRUE;
    }

    void HelloWorld()
    {
        MessageBox(NULL, TEXT(
    "Hello World"), TEXT("In a DLL"), MB_OK);
    }

    #ifdef _MANAGED
    #pragma managed(pop)
    #endif

     2. 编译成功!接下来我们便可以添加一个C#控制台项目了

         C#测试代码如下:

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Runtime.InteropServices;

    namespace TestDll
    {
        
    class Program
        {
            [DllImport(
    "myDll.dll")]
            
    public extern static void HelloWorld();

            
    static void Main(string[] args)
            {
                HelloWorld();
            }
        }
    }

      在这里我要特别指出的是两点:

    1) 必须使用如下命名空间

    using System.Runtime.InteropServices

    2) 对于原Dll文件中C方法的wrapper

            [DllImport("myDll.dll")]
            
    public extern static void HelloWorld();

    运行程序,会看到弹出Hello World对话框!

    技术改变世界
  • 相关阅读:
    【转】 java中Class对象详解和类名.class, class.forName(), getClass()区别
    106. Construct Binary Tree from Inorder and Postorder Traversal
    105. Construct Binary Tree from Preorder and Inorder Traversal
    107. Binary Tree Level Order Traversal II
    109. Convert Sorted List to Binary Search Tree
    108. Convert Sorted Array to Binary Search Tree
    110. Balanced Binary Tree
    STL容器迭代器失效问题讨论
    113. Path Sum II
    112. Path Sum
  • 原文地址:https://www.cnblogs.com/davidgu/p/2086024.html
Copyright © 2020-2023  润新知