Calling Function from custom dll

This topic contains 3 replies, has 2 voices, and was last updated by Profile photo of Dave Wyatt Dave Wyatt 1 year, 10 months ago.

  • Author
    Posts
  • #22170
    Profile photo of Never Summer
    Never Summer
    Participant

    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)

  • #22173
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    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
    Profile photo of Never Summer
    Never Summer
    Participant

    Thank you!

    I try that and it work!

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

  • #22204
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

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

You must be logged in to reply to this topic.