zoukankan      html  css  js  c++  java
  • c#调用c++的dll

    制作c++的dll

    // MyCppDll.cpp : 定义 DLL 应用程序的导出函数。
    
    // 这一句必须
    #include "stdafx.h"
    // 导入自己想要的头文件
    #include <windows.h>
    
    // 为函数加入以下声明即可导出:extern "C" extern __declspec(dllexport) 
    //	另外,加入以上声明后函數調用約定默认为“Cdecl”,若要强制指定为,请在函数的返回类型之后加入“__stdcall”关键字
    extern "C" extern __declspec(dllexport)  LPCWSTR __stdcall Hello(LPCWSTR lpTitle,LPCWSTR lpContent)
    {
    	MessageBox(NULL,lpContent,lpTitle,0);
    	return lpContent;
    }
    
    
    
    
    
    // 定义 DLL 应用程序的入口点。
    // 比如当dll刚被载入至内存或卸载时可以做一些事
    BOOL APIENTRY DllMain( HMODULE hModule,
    	DWORD  ul_reason_for_call,
    	LPVOID lpReserved
    	)
    {
    	switch (ul_reason_for_call)
    	{
    	case DLL_PROCESS_ATTACH:
    		Hello(L"",L"DLL_PROCESS_ATTACH");
    		break;
    	case DLL_THREAD_ATTACH:
    		Hello(L"",L"DLL_THREAD_ATTACH");
    		break;
    	case DLL_THREAD_DETACH:
    		Hello(L"",L"DLL_THREAD_DETACH");
    		break;
    	case DLL_PROCESS_DETACH:
    		Hello(L"",L"DLL_PROCESS_DETACH");
    		break;
    	}
    
    	return TRUE;
    }
    




    写c#

    using System;
    using System.Runtime.InteropServices;
    
    
    namespace MyCsharpConsoleApplication
    {
        class Program
        {
            [DllImport("MyCppDll", CallingConvention = CallingConvention.StdCall)]
            extern static string Hello(string title, string content);
    
            static void Main()
            {
                var ret = Hello(@"hello你好".ToAnsi(), @"theraphy大叮当".ToAnsi());
                Console.WriteLine(ret);
            }
        }
    
        static class Helper
        {
            /// <summary>
            /// 将Unicode字符串转换成多字节字符串
            /// </summary>
            /// <param name="content"></param>
            /// <returns></returns>
            public static string ToAnsi(this string content)
            {
                return System.Text.Encoding.Default.GetString(System.Text.Encoding.Unicode.GetBytes(content));
            }
        }
    }
    


    也可以直接声明Unicode编码传递

    using System;
    using System.Runtime.InteropServices;
    
    
    namespace MyCsharpConsoleApplication
    {
        class Program
        {
            [DllImport("MyCppDll", CallingConvention = CallingConvention.StdCall,CharSet = CharSet.Unicode)]
            extern static string Hello(string title, string content);
    
            static void Main()
            {
                var ret = Hello(@"hello你好", @"theraphy大叮当");
                Console.WriteLine(ret);
            }
        }
    }
    



    源码下载

  • 相关阅读:
    了解Web2.0必订阅之十大Blog[个人推荐]
    [J2ME Q&A]Target port denied to untrusted applications问题回应
    2005年Csdn十大最热门BLog作者排名第一?
    J2me流媒体技术实现讨论[1]
    液氮
    微分、差分和变分的概念
    Python mutable vs immutable (不可变对象 vs 可变对象)
    异戊烷
    免疫组化
    [导入]java escape unescape
  • 原文地址:https://www.cnblogs.com/beta2013/p/3377326.html
Copyright © 2011-2022 走看看