Calling Function from custom dll

Hello, everyone!

I have a problem with calling function in custom dll written on C (or C++).
The prototype of function: extern unsigned short _stdcall InitRndm (char *key_dev, int window_enable );
DLL name: testrndm.dll

i try to do it that:

$decl = @’
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate UInt16 InitRndmDelegate (string key_dev, Int16 window_enable );

    [DllImport("testrndm.dll")]
    public static extern UInt16 InitRndm(InitRndmDelegate callback);

'@

$verba = Add-Type -MemberDefinition $decl -Name “testrndm” -PassThru
#$verba::InitRndm(“A:”,0)
#$verba::InitRndmDelegate(“A:”,0)

This is tricky, since I can’t test with your code. However, I’m not sure where your InitRndmDelegate is coming from; I don’t see anything about a delegate in the C definition. Is your C function expecting an Ascii-encoded string? I also don’t tend to use -PassThru with Add-Type, so I’ll stick to what I’m familiar with in this reply.

I would try this:

Add-Type -TypeDefinition @'
    using System;
    using System.Runtime.InteropServices;

    public static class TestRndm
    {
        [DllImport("testrndm.dll", EntryPoint = "InitRndm", CharSet = CharSet.Ansi)]
        public static extern short InitRndm(string key_dev, int window_enable);
    }
'@

[TestRndm]::InitRndm('A:', 0)

Edit: forgot “extern”.

Thank you!

I try that and it work!

but, for what you use ‘EntryPoint =…’?

Habit, mainly. Since the C# method is also called InitRndm, EntryPoint is optional.