zoukankan      html  css  js  c++  java
  • DLL创建与调用(C#调用C++的DLL)

    1、C++中需要导出函数,函数定义处在返回值前加上:extern "C" __declspec(dllexport)

      C#调用:[DllImport("导出函数所在DLL名", EntryPoint = "函数名")]
           static extern unsafe 函数定义

      代码示例:

        C++导出: #define DllExport extern "C" __declspec(dllexport)

              DllExport void __stdcall GetVersion_SW(char* pVersion)  {  ……函数定义  }

        C# 调用:  [DllImport("DllExportDemo.dll", EntryPoint = "GetVersion_SW")]
                     static extern unsafe void GetVersion(char* pVersion);

              unsafe
                      {

                          IntPtr pStr = Marshal.AllocHGlobal(100);

                          GetVersion((char*)pStr);
                          string VersionStr = new string((SByte*)pStr);

                          Marshal.FreeHGlobal(pStr);
              }

    2、C++中需要导出,类定义处在类名前加上:__declspec(dllexport)

      C++调用:加入导出类所在头文件和导出类所在DLL的静态库文件(DLL名.lib)

           使用处引用该头文件后,和普通类一样使用。

      注:C#不能直接使用DLL中导出的C++类

      代码示例:

        C++导出: #define DllExport __declspec(dllexport)
              class DllExport MyClass
              {
                public:
                  MyClass();
                  ~MyClass();

                  void Show();

                  private:

              };

        C++调用: #include "MyClass.h" (MyClass类定义所在头文件)

              MyClass* testClass = new MyClass();

              testClass->Show();
      

     3、注意点:

      (1)、函数参数类型需按照所占位数一 一对应

        例:C#中的ulong对应C++中的ULONG64,而非ULONG。

        注:原因是C++中long、int等类型的长度和平台相关,C#中的long、int等类型是固定长度。

        

  • 相关阅读:
    Linux 命令详解(二)awk 命令
    Linux 命令详解(一)export 命令
    ngx_lua_API 指令详解(六)ngx.thread.spawn、ngx.thread.wait、ngx.thread.kill介绍
    ngx_lua_API 指令详解(五)coroutine.create,coroutine.resume,coroutine.yield 等集合指令介绍
    Git与GitHub学习笔记(三).gitignore文件忽略和删除本地以及远程文件
    高性能服务器架构(三):分布式缓存
    Kubernetes的node,NotReady 如何查问题,针对问题解决
    K8S 报 ErrImagePull k8s.gcr.io国内无法连接解决方法
    Quick deployment of Kubernetes
    Kubernetes 部署笔记
  • 原文地址:https://www.cnblogs.com/dhqy/p/8301577.html
Copyright © 2011-2022 走看看