lsalamon
lsalamon

Reputation: 8174

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

Upvotes: 0

Views: 2699

Answers (2)

Adriano Repetti
Adriano Repetti

Reputation: 67118

DllImportAttribute is for NATIVE imports. Your C++/CLI class is not native (ref class) so you do not have to import that in this way. Simply add a reference to MyClassLib.dll and use it as a standard, normal, simple .NET class (call MyClass.SIncrement() like you would do with a C# class).

Upvotes: 4

Mikant
Mikant

Reputation: 326

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

Upvotes: 2

Related Questions