• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C#与C++DLL的互操作

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

C#调用C++ DLL要点:

1.C++自己编写的函数必须为导出函数.
2.为把C++函数编译为导出函数,在函数前面加上 

extern "C" __declspec(dllexport)

extern "C":按C语言的进行编译
__declspec(dllexport):表示导出函数,另外导入函数为__declspec(dllimport)

 

 


C++项目属性:

无公共语言运行时支持

C/C++ => 高级:

1.编译为 => 编译为 C++ 代码 (/TP)

2.调用约定=>__stdcall (/Gz)    注意:调用约定必须是 stdcall、cdecl 或 thiscall 之一。

 

C++函数:

#include "stdafx.h"
#include "stdio.h"
extern "C" __declspec(dllexport) void PrintMsg(const char* msg)
{
    printf("我在C++里编写:PrintMsg.\n下面的字符串是C#传入的:%s\n", msg);
    return;
}

 

C#调用:

        static void Main(string[] args)
        {
            PrintMsg(@"C#夜未眠");

            Console.ReadKey();
        }

        #region 自定义DLL互操作:

        [DllImport(@"E:\code\ConsoleApplication3\Debug\ConsoleApplication3.dll",
            CallingConvention = CallingConvention.StdCall)]
        static extern void PrintMsg(string msg);

        #endregion

 

运行结果:

 

 

另外附加一个:

SayStdC();//这个函数在vs里点启动显示不出来,要进入exe文件目录点击exe执行才能看到

 

        //直接对标准微软C运行库中的函数进行平台调用
        [DllImport("user32.dll", EntryPoint = "MessageBox")]
        public static extern int MessageBox(int hwnd, string lpText, string lpCaption, int wType);

        [DllImport("msvcrt.dll",CallingConvention = CallingConvention.Cdecl)]
        static extern int puts(string msg);//puts函数将字符串传送到输入流中

        [DllImport("msvcrt.dll",CallingConvention = CallingConvention.Cdecl)]
        static extern int _flushall();//手动清除所有输入流

        public static void SayStdC()
        {
            puts("puts函数调用");
            _flushall();
        }

        public static void SayWinAPI()
        {
            MessageBox(0, "Hello C# Code!", "CSharp互操作", 0);
        }

 

运行效果:

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
转:C#PDFbox读取PDF内容发布时间:2022-07-10
下一篇:
C#开发高亮语法编辑器——TextBox,RichTextBox发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap