PoshCode Archive  Artifact [3b2cbc26ff]

Artifact 3b2cbc26ff86e7d35b268a969e0f65a887e83434c128a6b186046312894f8955:

  • File Add-PInvoke.ps1 — part of check-in [ae1d85cc64] at 2018-06-10 13:39:08 on branch trunk — This file was uploaded by a PowerGUI Script Editor Add-on. (user: Anonymous size: 1856)

# encoding: ascii
# api: powershell
# title: Add-PInvoke.ps1
# description: This file was uploaded by a PowerGUI Script Editor Add-on.
# version: 0.1
# type: function
# author: Anonymous
# license: CC0
# function: Add-PInvoke
# x-poshcode-id: 4290
# x-archived: 2017-05-22T01:45:39
# x-published: 2014-07-03T10:17:00
#
#
function Add-PInvoke
{
    <#
    .Synopsis
        Creates C# code to access a C function
    .Description
        Creates C# code to access a C function
    .Example
        Add-PInvoke -Library User32.dll -Signature GetSystemMetrics(uint Metric)
    .Parameter Library
        A C Library containing code to invoke
    .Parameter Signature
        The C# signature of the external method
    .Parameter OutputText
        If Set, retuns the source code for the pinvoke method.
        If not, compiles the type. 
    #>
    param(
    [Parameter(Mandatory=$true, 
        HelpMessage="The C Library Containing the Function, i.e. User32")]
    [String]
    $Library,
    
    [Parameter(Mandatory=$true,
        HelpMessage="The Signature of the Method, i.e. int GetSystemMetrics(int Metric")]
    [String]
    $Signature,
    
    [Switch]
    $OutputText
    )
    
    process {
        if ($Library -notlike "*.dll*") {
            $Library+=".dll"
        }
        if ($signature -notlike "*;") {
            $Signature+=";"
        }
        if ($signature -notlike "public static extern*") {
            $signature = "public static extern $signature"
        }
        
        $MemberDefinition = "[DllImport(`"$Library`")]
$Signature"
        
        if (-not $OutputText) {
            Add-Type -PassThru -Name "PInvoke$(Get-Random)" `
                -MemberDefinition $MemberDefinition
        } else {
            $MemberDefinition
        }
    }
}