Created
July 27, 2019 16:31
-
-
Save dfinke/171d8d06c61fab0d301de1bca3bd5578 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Import-Module PSStringScanner | |
function ConvertFrom-RustToPInvoke { | |
param( | |
[Parameter(Mandatory)] | |
$DllName, | |
[Parameter(Mandatory)] | |
$content | |
) | |
$parseResult = $(foreach ($line in $content) { | |
$ss = New-PSStringScanner $line | |
if($ss.Check('pub extern "C"')) { | |
$null = $ss.ScanUntil('fn ') | |
$functionName = $ss.ScanUntil('(?=\()') | |
$null = $ss.Scan("\(") | |
$parameters = $ss.ScanUntil('(?=\))') | |
$null = $ss.Scan('-> ') | |
$returnType = $ss.ScanUntil('(?= {)') | |
#$ss | |
$params = foreach ($parameter in $parameters.Split(",")) { | |
$Name,$Type = $parameter.Split(':') | |
[PSCustomObject][Ordered]@{ | |
Name=$Name.Trim() | |
Type=$Type.Trim() | |
} | |
} | |
[PSCustomObject][Ordered]@{ | |
FunctionName = $functionName | |
Parameters = $params | |
Type = $returnType | |
} | |
} | |
}) | |
$RustToCSharpTypeMap= @{ | |
'i32' = 'Int32' | |
} | |
$CSParams = ($parseResult.Parameters | % { | |
"{0} {1}" -f ($RustToCSharpTypeMap.($_.Type)), $_.Name | |
}) -join ", " | |
@" | |
[DllImport("$($dllname)")] | |
public static extern $($RustToCSharpTypeMap.($parseResult.Type)) $($parseResult.FunctionName)($($CSParams)); | |
"@ | |
} | |
return | |
ConvertFrom-RustToPInvoke -DllName "ps_to_rust" -Content @" | |
#[no_mangle] | |
pub extern "C" fn add_numbers(number1: i32, number2: i32) -> i32 { | |
number1 + number2 | |
} | |
"@ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment