Calling C# (.NET6) from Ansi C [DllExport]

211 views Asked by At

following example:

public static class DLLExportMethode
{
    [DllExport("add", CallingConvention = CallingConvention.StdCall)]
    public static int Add(int left, int right)
    {
        return left + right;
    }
}

Errors:

Severity Code Description Project File Line Suppression State

Error CS0246 The type or namespace name 'DllExportAttribute' could not be found (are you missing a using directive or an assembly reference?) CallingCSharpFromAnsiC.Library

Error CS0246 The type or namespace name 'DllExport' could not be found (are you missing a using directive or an assembly reference?) CallingCSharpFromAnsiC.Library

Error CS1069 The type name 'CallingConvention' could not be found in the namespace 'System.Runtime.InteropServices'. This type has been forwarded to assembly 'System.Runtime.InteropServices, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' Consider adding a reference to that assembly. CallingCSharpFromAnsiC.Library

but something is missing?

Does anyone have a simple example or know what is missing? Or how the syntax is correct. I would not want to use third party libraries for export.

1

There are 1 answers

0
Sean K On

Your fundamental problem is that a native C executable has no .NET runtime, and can't directly call a C# dll. What you really need to do is have a C dll that is loaded by a C# executable, and you use P/Invoke to generate function pointers for C# methods that can be passed to your C code.

See this for a minimalistic example Using PInvoke in C# with function pointer and delegate

Depending on what you are trying to accomplish, you may want a simple C# application that loads any other C# dlls you want your C code to be able to call, create delegates for whatever you need, call a C function to provide all the function pointers to the native C code, and finally call a entry point in your C dll (i.e. what would have been your C main).

You can also get quite fancy with reflecting objects to get function pointers for methods against specific objects (i.e. non-static), but from your question I think you are only looking to call static methods.