PropertyGroup节点添加PublishAot

<PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <PublishAot>true</PublishAot>
</PropertyGroup>

需要导出的方法添加UnmanagedCallersOnly特性

public class ClassTest
{
    [UnmanagedCallersOnly(EntryPoint = "Add")]
    public static int Add(int a, int b)
    {
        return a + b;
    }
    [UnmanagedCallersOnly(EntryPoint = "AddString")]
    public static IntPtr AddString(IntPtr a, IntPtr b)
    {
        var s1 = Marshal.PtrToStringAnsi(a);
        var s2 = Marshal.PtrToStringAnsi(b);
        return Marshal.StringToHGlobalAnsi(s1 + s2);
    }
    [UnmanagedCallersOnly(EntryPoint = "WriteLine")]
    public static int WriteLine(IntPtr pStr)
    {
        try
        {
            var str = Marshal.PtrToStringAnsi(pStr);
            Console.WriteLine(str);
        }
        catch
        {
            return -1;
        }
        return 0;
    }
    [UnmanagedCallersOnly(EntryPoint = "HttpServe")]
    public static void HttpServe()
    {
        var serve = new HttpListener();
        serve.Prefixes.Add("http://127.0.0.1:8080/");
        serve.Start();
        serve.BeginGetContext(res => Result(serve, res), null);
        Console.WriteLine($"服务端初始化完毕,正在等待客户端请求,时间:{DateTime.Now.ToString()}\r\n");
        Console.ReadKey();
    }
    private static void Result(HttpListener serve, IAsyncResult asyncResult)
    {
        //继续异步监听
        serve.BeginGetContext(res => Result(serve, res), null);

        var guid = Guid.NewGuid().ToString();
        Console.ForegroundColor = ConsoleColor.White;
        Console.WriteLine($"接到新的请求:{guid},时间:{DateTime.Now.ToString()}");
        //获得context对象
        var context = serve.EndGetContext(asyncResult);
        var request = context.Request;
        var response = context.Response;
        context.Response.ContentType = "text/plain;charset=UTF-8";//告诉客户端返回的ContentType类型为纯文本格式,编码为UTF-8
        context.Response.ContentEncoding = Encoding.UTF8;
        Console.WriteLine(request.RawUrl);
        if (request.HttpMethod == "POST")
        {
            //request.InputStream
            using (var stream = request.InputStream)
            {
                using (var reader = new StreamReader(stream))
                {
                    var body = reader.ReadToEnd();
                    Console.WriteLine($"请求body:{body}\n");
                }
            }
        }
        switch (request.RawUrl)
        {
            case "/":
                var returnByteArr = Encoding.UTF8.GetBytes($"返回信息:{guid}");
                try
                {
                    using (var stream = response.OutputStream)
                    {
                        //把处理信息返回到客户端
                        stream.Write(returnByteArr, 0, returnByteArr.Length);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"网络异常:{ex.ToString()}");
                }
                break;
            default:
                response.StatusCode = (int)HttpStatusCode.NotFound;
                response.OutputStream.Close();
                response.Close();
                break;
        }


    }
}

调用代码

#include <iostream>
#include <string>
#include <Windows.h>

int main()
{
    std::cout << "Hello World!\n";
#if NDEBUG
    HMODULE handle = LoadLibraryA("libs/NativeLibrary.dll");
#else
    HMODULE handle = LoadLibraryA("../NativeLibrary/bin/Release/net8.0/publish/win-x64/NativeLibrary.dll");
#endif

    if (handle != NULL) {
        //为Add声明函数指针Add
        typedef int (*Add)(int, int);

        typedef char* (*AddString)(const char*, const char*);

        //为WriteLine声明函数指针WriteLine
        /*typedef int (*WriteLine)(std::string);*/
        typedef int (*WriteLine)(const char*);

        typedef void (*HttpServe)();

        Add sum = (Add)GetProcAddress(handle, "Add");
        WriteLine writeLine = (WriteLine)GetProcAddress(handle, "WriteLine");
        AddString addString = (AddString)GetProcAddress(handle, "AddString");
        HttpServe httpServe = (HttpServe)GetProcAddress(handle, "HttpServe");

        int a = 100;
        int b = 50;
        std::cout << "sum=" << sum(a, b) << std::endl;
        int res = writeLine("Hello C#!");
        std::cout << res << std::endl;
        std::string c = std::to_string(a);
        std::string d = std::to_string(b);
        std::cout << c << std::endl;
        std::cout << addString(c.data(), d.data()) << std::endl;
        
        httpServe();
    }
    return 0;
}