Search code examples
c#.netc++-climanaged

Calling C++/CLI static member of public ref class from C#


I'm having trouble implementing the correct way to use this prototype implemented in C + + / CLI using CSharp.

C++/CLI implementation:

// 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;
    }
}

Usage implementation:

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
        }
    }
}

Solution

  • number = MyClass.SIncrement(number); and no P/Invoke