从 C# 调用 C++ 泛型方法

Calling c++ generic method from C#

我创建了一个C++ 64位库如下

// UnManagedCLI.h

#pragma once

using namespace System;
using namespace System::Runtime::InteropServices;

namespace UnManagedCLI {

    [DllImport("msvcrt.dll", EntryPoint = "memset", CallingConvention = CallingConvention::Cdecl, SetLastError = false)]
    extern IntPtr MemSet(IntPtr dest, int c, int count);

    //[System::Runtime::CompilerServices::ExtensionAttribute]
    public ref class Unmanaged sealed
    {
    public:
        static void Free(void* unmanagedPointer)
        {
            Marshal::FreeHGlobal(IntPtr(unmanagedPointer));
        }

        generic <typename T> where T : value class
            static IntPtr New(int elementCount)
        {
            return Marshal::AllocHGlobal(sizeof(T) * elementCount);
        }

         generic <typename T> where T : value class
            static IntPtr NewAndInit(int elementCount)
        {
            int sizeInBytes = sizeof(T) * elementCount;
            IntPtr newArrayPtr = Marshal::AllocHGlobal(sizeInBytes);
            MemSet(newArrayPtr, 0 , sizeInBytes);
            return newArrayPtr;
        }

        generic <typename T> where T : value class
            static void* Resize(void* oldPointer, int newElementCount)
        {
            return Marshal::ReAllocHGlobal(IntPtr(oldPointer), 
                IntPtr((int) sizeof(T) * newElementCount)).ToPointer();
        }
    };
}

我从 C# 中将其作为参考,检查构建中的不安全代码,然后在 main 中执行此操作:

using UnManagedCLI;

unsafe class TestWriter
{
    static void Main()
    {
        Unmanaged un;

        //I can't access any of the C++ methods in here?
    }
}

当我说 un. 时,我没有看到 C++/CLI 库中的任何方法?它构建并运行良好,但我根本无法访问 C++。

您的 C+++/CLI class(非托管)的所有方法都是静态的。尝试在 C# 中使用 Unmanaged.Method 语法(您不必创建对象)。