C# 调用C++动态链接库 之一 传入参数

来源:互联网 发布:mac无损播放器哪个好 编辑:程序博客网 时间:2024/06/11 13:26

请看。


C++:

编写C++库文件:


// testdll.cpp : 定义 DLL 应用程序的导出函数。
//


#include "stdafx.h"
#include "stdio.h"


extern "C"  void  test(char* p){
if(NULL != p){
OutputDebugString(p);
printf("%s\n",p);
}
else{
printf("empty p \n");
}


}


模块定义


LIBRARY
EXPORTS 
test @1


C#

    static class Program    {        /// <summary>        /// 应用程序的主入口点。        /// </summary>        [STAThread]        static void Main()        {            Console.WriteLine("start");            //分配内存            var data = Marshal.StringToHGlobalAnsi(string.Format("hello world"));            test(data);            //释放            Marshal.FreeHGlobal(data);            Console.WriteLine("end");            Console.Read();        }        [DllImport("testdll.dll",CallingConvention = CallingConvention.Cdecl)]        private static extern void test(IntPtr p);    }


运行结果



原创粉丝点击