views:

455

answers:

4

Hello,

how can we export c# methods?

I hava a dll and I want to use its methods in the Python language with the ctypes module. Because I need to use the ctypes module, I need to export the c# methods for them to be visible in Python.

So, how can I export the c# methods (like they do in c++)?

+1  A: 

With the normal Python implementation ("CPython"), you can't, at least not directly.

You could write native C wrappers around our C# methods using C++/CLI, and call these wrappers from Python.

Or, you could try IronPython. This lets you run Python code and call code in any .Net language, including C#.

oefe
I want to use Python itself and not an extra implementation of it like IronPython.
aF
+1  A: 

(This may no longer be relevant since SLaks has found that ingenious link, but I'll leave an edited version for reference...)

The "normal" way of exposing .NET/C# objects to unmanaged code (like Python) is to create a COM-callable wrapper for the C# DLL (.NET assembly), and call that using Python's COM/OLE support. To create the COM-callable wrapper, use the tlbexp and/or regasm command-line utilities.

Obviously, however, this does not provide the C/DLL-style API that SLaks' link does.

itowlson
Actually, it is possible. See my answer.
SLaks
+14  A: 

Contrary to popular belief, this is possible.
See here.

SLaks
I used the dllexp.exe to see the exported methods from the C# dll that the template creates and it didn't happear the method.. Is there a way for the C# dll methods to be visible externally in a program like dllexp.exe?
aF
tks for the answer ;)
aF
+1  A: 

That's not possible. If you need DLL exports you'll need to use the C++/CLI language. For example:

public ref class Class1 {
public:
  static int add(int a, int b) {
      return a + b;
  }
};

extern "C" __declspec(dllexport) 
int add(int a, int b) {
  return Class1::add(a, b);
}

The class can be written in C# as well. The C++/CLI compiler emits a special thunk for the export that ensures that the CLR is loaded and execution switches to managed mode. This is not exactly fast.

Writing [ComVisible(true)] code in C# is another possibility.

Hans Passant
Actually, it is possible. See my answer.
SLaks
Please consider removing/changing the answer. As SLaks pointed out Reverse P/Invoke is possible (although you probably don't want to use it for everything and need to understand what happens if you use it).
Benjamin Podszun
Meh, neither the article nor the downloadable source code explains how it works. I'll wait for confirmation from the OP.
Hans Passant