Ivan
Ivan

Reputation: 7746

Calling c++ generic method from C#

I created a C++ 64-bit library as follows

// 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();
        }
    };
}

From C# I include it as a reference, check unsafe code in the build, and then in main do this:

using UnManagedCLI;

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

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

when I say un. I don't see any of the methods in the C++/CLI library? It builds and runs fine, but I cannot access the C++ at all.

Upvotes: 0

Views: 188

Answers (1)

Sebacote
Sebacote

Reputation: 699

All the methods of your C+++/CLI class (Unmanaged) are static. Try using the Unmanaged.Method syntax in C# (you don't have to create an object).

Upvotes: 2

Related Questions