从C#调用公共ref类的C++/CLI静态成员

本文关键字:C++ CLI 静态成员 类的 ref 调用 | 更新日期: 2023-09-27 18:27:42

我在使用CSharp实现在C++/CLI中实现的原型的正确使用方法时遇到问题。

C++/CLI实现:

// MyClassLib.h
#pragma once
using namespace System;
namespace MyClassLib 
{
    public ref class MyClass
    {
    public:
        int Increment(int number);
        static int SIncrement(int number);
    };
}
// This is the main DLL file.
#include "stdafx.h"
#include "MyClassLib.h"
namespace MyClassLib
{
    int MyClass::Increment(int number)
    {
        return number+1;
    }
    int MyClass::SIncrement(int number)
    {
        return number+1;
    }
}

使用实现:

using System;
using System.Runtime.InteropServices;
using MyClassLib;
namespace UseClassLib
{
    class Program
    {
        [DllImport("MyClassLib.dll")]
        public static extern int SIncrement(int number);
        static void Main(string[] args)
        {
            MyClass mc = new MyClass();
            int number = 1;
            number = mc.Increment(number); // increment ok
            number = SIncrement(number); // System.EntryPointNotFoundException here
        }
    }
}

从C#调用公共ref类的C++/CLI静态成员

DllImportAttribute用于NATIVE导入。您的C++/CLI类不是本机类(ref class),因此不必以这种方式导入。只需添加对MyClassLib.dll的引用,并将其用作标准、普通、简单的.NET类(像对待C#类那样调用MyClass.SIncrement())。

number = MyClass.SIncrement(number);并且没有P/Invoke