c#调用c++类库

c#调用c++类库,第1张

c#调用c++类库

1.c++ 创建类库(无公共语言运行时)

2.添加类
mydll.h文件
#pragma once
extern "C" _declspec(dllexport) int _stdcall add(int a,int b);
mydll.cpp文件
#include "stdafx.h"
#include "mydll.h"
int _stdcall add(int a, int b)
{
    return (a+b);
}

2.c#

using System;
using System.Runtime.InteropServices;

namespace ConsoleAppTemp
{
    class Program
    {
        [Dllimport("DllTest.dll")] //Dllimport 必须引用using System.Runtime.InteropServices;
        public static extern int add(int a, int b);

        //可以通过EntryPoint特性指定函数入口,然后为函数定义别名
        [Dllimport("HelloWorldLib.dll", EntryPoint = "add")]
        public static extern int CustomName(int a, int b);
        static void Main(string[] args)
        {
            int a = add(1, 2);
            Console.WriteLine("输出结果为:" + a.ToString());
            //跟上面是一样的
            int b = add(1, 2);
            Console.WriteLine("输出结果为:" + b.ToString());
            Console.ReadKey();
        }
    }
}

参考:一、C++类库与C#类库相互调用 - 十色 - 博客园 (cnblogs.com)

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5702635.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存