C
C#3y ago
Pillow

❔ C# library usable from python

I was wondering how to do this, and stumbled upon https://stackoverflow.com/a/29854281 which answered the question, but then caused two new ones. 1. can this be done without .NET installed on the user's machine 2. how do I create a project for that in VS? Do I just choose class library or something else?
Stack Overflow
Calling a C# library from python
Anyone can share a working example on how to call a simple C# library (actually its WPF) from python code? (I have tried using IronPython and had too much trouble with unsupported CPython library my
17 Replies
ero
ero3y ago
in current year you would probably use NativeAOT
static class Exports
{
[UnmanagedCallersOnly(EntryPoint = "add")]
public static int Add(int a, int b) => a + b;
}
static class Exports
{
[UnmanagedCallersOnly(EntryPoint = "add")]
public static int Add(int a, int b) => a + b;
}
<PublishAot>true</PublishAot>
<PublishAot>true</PublishAot>
dotnet publish -c Release -r win-x64 and then you can call that like you would any other c or c++ library (however that may be done in python)
Pillow
PillowOP3y ago
oh amazing no .NET needed once published?
ero
ero3y ago
yup
Pillow
PillowOP3y ago
ooo oh and one last thing, how do I create a project for this in VS2022, what option do I choose?
reflectronic
reflectronic3y ago
that answer is a little bit outdated oh, the chat didn’t scroll 😰 you would just make a class library project
Pillow
PillowOP3y ago
alr ty!
reflectronic
reflectronic3y ago
adding PublishAot to the csproj file is all you need to enable it when you dotnet publish you’ll get the self-contained DLL file that you can use from python
Pillow
PillowOP3y ago
alright amazing, thank you both!!
reflectronic
reflectronic3y ago
you need to install the C++ tools if you haven’t already
Pillow
PillowOP3y ago
i've got that yep it doesn't seem to want to work, is this c# correct?
using System.Runtime.InteropServices;

namespace ToasterMap
{
static class ToasterMap
{
[UnmanagedCallersOnly(EntryPoint = "add")]
public static int Add(int a, int b) => a + b;
}
}
using System.Runtime.InteropServices;

namespace ToasterMap
{
static class ToasterMap
{
[UnmanagedCallersOnly(EntryPoint = "add")]
public static int Add(int a, int b) => a + b;
}
}
and i've got the <PublishAot>true</PublishAot> in the propertygroup in the csproj
ero
ero3y ago
and you're actually publishing? and not just building?
Pillow
PillowOP3y ago
running dotnet publish -c Release -r win-x64
Pillow
PillowOP3y ago
and checking via dumpbin, there seems to be nothing
ero
ero3y ago
maybe i'm wrong but i'm pretty sure nativeaot was only added in .net 7
Pillow
PillowOP3y ago
ahhhh i'm running 6 do I need to update or can I use something else?
Pillow
PillowOP3y ago
YES!! I just needed .net 7!!
Accord
Accord3y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.

Did you find this page helpful?