Hello World for Pinvoke and Native Calls

2019-03-03 15:39发布

问题:

I am trying to do a very basic hello world for Pinvoke and native calls.
I create a single solution with 2 projects (one for the dll and one for the universal windows app)

So I end up with a project heirachy like this

There is one method in my dll (file NativeCalls.cpp):

#include "pch.h"
#include "NativeCalls.h"
#include <stdio.h>

MYAPI void print_line(const char* str) {
    printf("%s\n", str);
}

On the C# side of things I have my NativeCalls.cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;



namespace MSSurfaceHubMonitoring
{

    public static class NativeCalls
    {

        [DllImport("NativeCalls.dll")]
        private static extern void print_line(string str);

        public static void sayHelo()
        {
            print_line("Hello, PInvoke!");
        }
    }
}

At this point I will build and run it but get an error that it cannot find the dll

However I believe it to be the dependency and not the dll it self. I have changed the output directory of the dll to be in the root of where the UW app runs from (\bin\x86) so it really should be finding it. So like I said I think its the dependencies and not the actual dll.

Here is what I see in Dependency Walker But I have installed all c++ packages I can get my hands on so I dont understand how to get the missing dependencies. Plus this is just a hello world, why do I need all these libraries.

FYI My dll project is NOT referenced by the UW app. Im not sure thats needed or not? I dont think so though since this a runtime thing, so as long as the dll is there it should find it and read it. But regardless if I do try to add the project as a reference I get this error:

回答1:

The biggest help to me was finding these method declarations (not even in the class)

extern "C" {
    __declspec(dllexport) int getPageSize()
    {
        SYSTEM_INFO siSysInfo;
        GetSystemInfo(&siSysInfo);
        return siSysInfo.dwPageSize;
    }
}

extern "C" {
    __declspec(dllexport) Windows::Foundation::Collections::IMap<Platform::String^, int> ^getSystemInfo()
    {
        SYSTEM_INFO siSysInfo;
        GetSystemInfo(&siSysInfo);

        IMap<String^, int> ^ret =
            ref new Platform::Collections::Map<String^, int>;
        ret->Insert("oemId", siSysInfo.dwOemId);
        ret->Insert("cpuCount", siSysInfo.dwNumberOfProcessors);
        ret->Insert("pageSize", siSysInfo.dwPageSize);
        ret->Insert("processorType", siSysInfo.dwProcessorType);
        ret->Insert("maxApplicationAddress", siSysInfo.lpMinimumApplicationAddress);
        ret->Insert("minApplicationAddress", siSysInfo.lpMaximumApplicationAddress);
        ret->Insert("activeProcessorMask", siSysInfo.dwActiveProcessorMask);
        return ret;
    }

but in the end I was creating wrappers for things I didnt need to. in c# you can directly call the native methods without the need for a seperate dll or component project.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;


namespace Monitoring
{

    public static class NativeCallsWrapper
    {
        private static SYSTEM_INFO sysInfo = new SYSTEM_INFO();
        private static MEMORYSTATUSEX mem = new MEMORYSTATUSEX();

        [DllImport("kernel32.dll", SetLastError = false)]
        public static extern void GetSystemInfo([In, Out] SYSTEM_INFO Info);

        [return: MarshalAs(UnmanagedType.Bool)]
        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool GlobalMemoryStatusEx([In, Out] MEMORYSTATUSEX lpBuffer);

        static NativeCallsWrapper()
        {
            GetSystemInfo(sysInfo);
            GlobalMemoryStatusEx(mem);
        }

        [StructLayout(LayoutKind.Explicit)]
        public struct SYSTEM_INFO_UNION

        {

            [FieldOffset(0)]
            public UInt32 OemId;
            [FieldOffset(0)]
            public UInt16 ProcessorArchitecture;
            [FieldOffset(2)]
            public UInt16 Reserved;
        }

        public struct SYSTEM_INFO

        {

            public SYSTEM_INFO_UNION CpuInfo;
            public UInt32 PageSize;
            public UInt32 MinimumApplicationAddress;
            public UInt32 MaximumApplicationAddress;
            public UInt32 ActiveProcessorMask;
            public UInt32 NumberOfProcessors;
            public UInt32 ProcessorType;
            public UInt32 AllocationGranularity;
            public UInt16 ProcessorLevel;
            public UInt16 ProcessorRevision;
        }

        [StructLayout(LayoutKind.Sequential)]
        public class MEMORYSTATUSEX
        {
            public uint dwLength;
            public uint dwMemoryLoad;
            public ulong ullTotalPhys;
            public ulong ullAvailPhys;
            public ulong ullTotalPageFile;
            public ulong ullAvailPageFile;
            public ulong ullTotalVirtual;
            public ulong ullAvailVirtual;
            public ulong ullAvailExtendedVirtual;
            public MEMORYSTATUSEX()
            {
                this.dwLength = (uint)Marshal.SizeOf(typeof(MEMORYSTATUSEX));
            }
        }

        public static GeneralStatistics getGeneralStatistics()
        {
            GeneralStatistics generalStatistics = new GeneralStatistics();
            generalStatistics.numberOfProcesses = (int)sysInfo.NumberOfProcessors;
            generalStatistics.memoryTotal = mem.ullTotalPhys / 1048;
            generalStatistics.memoryInUse = (mem.ullTotalPhys - mem.ullAvailPhys) / 1048;
            return generalStatistics;
        }
    }
}