Calling Function from custom dll

Welcome Forums General PowerShell Q&A Calling Function from custom dll

This topic contains 3 replies, has 2 voices, and was last updated by

3 years, 12 months ago.

  • Author
  • #22170

    Points: 0
    Rank: Member

    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 = @'
    public delegate UInt16 InitRndmDelegate (string key_dev, Int16 window_enable );

    public static extern UInt16 InitRndm(InitRndmDelegate callback);

    $verba = Add-Type -MemberDefinition $decl -Name "testrndm" -PassThru

  • #22173

    Points: 0
    Rank: Member

    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".

  • #22203

    Points: 0
    Rank: Member

    Thank you!

    I try that and it work!

    but, for what you use 'EntryPoint =...'?

  • #22204

    Points: 0
    Rank: Member

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

The topic ‘Calling Function from custom dll’ is closed to new replies.