Home > Backend Development > C++ > How Can I Call a Native .NET Library from Python?

How Can I Call a Native .NET Library from Python?

Barbara Streisand
Release: 2025-01-05 15:35:40
Original
932 people have browsed it

How Can I Call a Native .NET Library from Python?

Calling a Native .NET Library from Python

Your goal is to execute a .NET library from within your Python code. To achieve this, we'll avoid using IronPython and instead explore the possibility of calling C# code from Python.

First, you'll need to install the "UnmanagedExports" NuGet package into your .NET project. This package allows you to export .NET methods without COM interoperability.

Here's a modified example of your C# code:

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using RGiesecke.DllExport;

class Test
{
    [DllExport("add", CallingConvention = CallingConvention.Cdecl)]
    public static int TestExport(int left, int right)
    {
        return left + right;
    }
}
Copy after login

Once compiled, you can load the .dll into your Python code and access the exported methods:

import ctypes
a = ctypes.cdll.LoadLibrary(source)
a.add(3, 5)
Copy after login

This will invoke the TestExport method in your C# library, returning the sum of the two numbers passed to it.

The above is the detailed content of How Can I Call a Native .NET Library from Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template