Win32 api call GetShortPathName error in f #

I can get this code to work in an interactive environment, but it crashes when I run the code from the debugger or from the .exe file

Forgot the error: FatalExecutionEngineError detected! The runtime has encountered a fatal error. The error address was 0x6c9781b0, in the stream 0x1104. Error Code: 0xc0000005. This error may be an error in the CLR or in unsafe or unverifiable portions of user code. Common sources of this error include user marshaling errors for COM-interop or PInvoke, which can damage the stack.

Using .net 4.5

open System.IO
open System.Runtime.InteropServices
open System.Text

[<DllImport("kernel32.dll",CharSet = CharSet.Auto, SetLastError=true)>]
extern uint32 GetShortPathName(
    [<MarshalAs(UnmanagedType.LPWStr)>] string longpath, 
    [<MarshalAs(UnmanagedType.LPWStr)>] StringBuilder shortpath, 
    [<MarshalAs(UnmanagedType.U4)>] uint32  item)

let MakeShortName(longPath : string) =
    let sb =  StringBuilder()
    let currPath = longPath
    let item = 1024u

   // let blah = ""
    //win32 assigns shortPath
    let blah32 = GetShortPathName(currPath, sb, item)

    sb.ToString()

[<EntryPoint>]
let main argv = 

    let path = @"C:\dev\shortName\shortName"
    let shorty = MakeShortName path
    printfn "%s" shorty 
    let x = System.Console.ReadKey()

    0

Interactive env


$ (me alt + input of two above functions)

val GetShortPathName: string * StringBuilder * uint32 → uint32 val MakeShortName: string → string

$MakeShortName @ "C:\dev\shortName\shortName";; val it: string = "C:\dev\SHORTN ~ 1\SHORTN ~ 1"

+5
2

.

@ 32

. :

open System.IO
open System.Runtime.InteropServices
open System.Text

[<DllImport("kernel32.dll",CharSet = CharSet.Auto, SetLastError=true)>]
extern int GetShortPathName(
    string longpath, 
    StringBuilder shortpath, 
    int  item)

let MakeShortName(longPath : string) =
    let sb =  StringBuilder()
    let currPath = longPath
    let item = 1024

   // let blah = ""
//win32 assigns shortPath
    let blah32 = GetShortPathName(currPath, sb, item)

    sb.ToString()

[<EntryPoint>]
let main argv = 

let path = @"C:\dev\shortName\shortName"
let shorty = MakeShortName path
printfn "%s" shorty 
let x = System.Console.ReadKey()

0
+4

Win32 . , :

let MakeShortName(longPath : string) =
    let maxSize = uint32 <| longPath.Length + 16
    let sb =  new StringBuilder("", int32 maxSize)
    let len = GetShortPathName(longPath, sb, maxSize)
    sb.ToString(0, int32 len)
0

All Articles