Win32 api调用f#中的错误GetShortPathName

Dav*_*son 5 winapi f#

我可以让这段代码在交互式环境中运行但是当我从调试器或.exe文件运行代码时它会崩溃

忘记了错误:检测到FatalExecutionEngineError!运行时遇到了致命错误.错误的地址是0x6c9781b0,在线程0x1104上.错误代码是0xc0000005.此错误可能是CLR中的错误,也可能是用户代码的不安全或不可验证部分中的错误.此错误的常见来源包括COM-interop或PInvoke的用户编组错误,这可能会破坏堆栈.

使用.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
Run Code Online (Sandbox Code Playgroud)

互动环境


$(我alt +进入以上两个功能)

val GetShortPathName:string*StringBuilder*uint32 - > uint32 val MakeShortName:string - > string

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

Dav*_*son 4

修复。

我只是烂@ win 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
Run Code Online (Sandbox Code Playgroud)