首页 > 编程语言 >C# 调用C++ 动态连接库

C# 调用C++ 动态连接库

时间:2022-11-02 17:16:06浏览次数:47  
标签:调用 C# Sum System C++ dll int using DLL

#pragma once
#define DLL_API __declspec(dllimport)
extern "C" DLL_API int __stdcall Sum(int a, int b);
operation.h
#include "pch.h"
#include "operation.h"//一定要添加头文件,不然会报错 System.EntryPointNotFoundException:“无法在 DLL“Operation.dll”中找到名为“Sum”的入口点。”

int __stdcall Sum(int a, int b)
{
    if (a - (int)a != 0 || b - (int)b != 0)
    {
        //cout << "请输入整数" << endl;
        return -1;
    }
    return a + b;
}
operation.cpp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp
{
    class Program
    {
        [DllImport("Operation.dll", EntryPoint = "Sum",
        ExactSpelling = false, CallingConvention = CallingConvention.StdCall)]
        public extern static int Sum(int a,int b);
        static void Main(string[] args)
        {
            int a = 1, b = 2, c;
            c = Sum(a, b);
            Console.WriteLine($"a + b = {c}");
            Console.ReadKey();
        }
    }
}
Program.cs

运行结果

注意两点。

1.源文件一定要添加头文件,否则报错说 System.EntryPointNotFoundException:“无法在 DLL“XXX.dll”中找到名为“XXX”的入口点。”

2.32位的dll一定要用32位的平台运行,反之64位也一样。否则报错说 System.BadImageFormatException:“试图加载格式不正确的程序。 (异常来自 HRESULT:0x8007000B)”

标签:调用,C#,Sum,System,C++,dll,int,using,DLL
From: https://www.cnblogs.com/lizhiqiang0204/p/16851603.html

相关文章