在c#中使用c++函数

using a c++ function in c#

本文关键字:c++ 函数      更新时间:2023-10-16

我在c++中定义了一个函数,我想把它包含在一些c#gui中。这就是我所做的:

在cpp文件中:

extern "C"             //No name mangling
__declspec(dllexport)  //Tells the compiler to export the function
int                    //Function return type     
__cdecl                //Specifies calling convention, cdelc is default, 
                   //so this can be omitted 
test(int number){
    return number + 1;
}

在cs文件中:

...
using System.Runtime.InteropServices;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
        }
        private void button1_Click(object sender, EventArgs e)
        {
            label1.Text = test(9);
        }
    }
    public static class NativeTest
    {
        private const string DllFilePath = @"c:test.dll";
        [DllImport(DllFilePath , CallingConvention = CallingConvention.Cdecl)]
        static extern int test(int a);
    }
}

我得到这个错误:

错误1当前上下文第28行中不存在名称"test"

感谢提供的任何帮助

感谢

您需要调用NativeTest.test(),而不仅仅是test()