Access C++ static methods from C#
Asked Answered
T

1

12

Say you have following C++ code:

extern "C" {
    void testA(int a, float b) {
    }

    static void testB(int a, float b){
    }
}

I want to access this in my C# project using DllImport:

class PlatformInvokeTest
{
    [DllImport("test.so")]
    public static extern void testA(int a, float b);
    [DllImport("test.so")]
    internal static extern void testB(int a, float b);

    public static void Main() 
    {
        testA(0, 1.0f);
        testB(0, 1.0f);
    }
}

This works perfectly fine for testA, but testB fails throwing an EntryPointNotFoundException.

Can I access testB from my C# code? How?

Triphylite answered 23/2, 2017 at 8:58 Comment(1)
A function declared static at the global scope has no external linkage so can never be exported. You'll have to remove static. You might be confusing it with declaring a class member function, declaring it static does something very different.Tentation
P
11

static does not mean the same in C++ as it does in C#. At namespace scope, static gives a name internal linkage, meaning that it is only accessible within the translation unit that contains the definition. Without static, it has external linkage, and is accessible in any translation unit.

You will need to remove the static keyword when you want to use DllImport

Profess answered 23/2, 2017 at 9:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.