简体   繁体   中英

How to pass a string containing a file path from C# to a function in a Pascal DLL requiring a PChar argument?

How can I pass a string containing a file path from C# to a function in a Pascal DLL requiring a PChar argument?

The Pascal DLL has a "FileExists" call that checks if the Argument (AFile: PChar) exists as a file. I've imported the dll succesfully like this:

[DllImport(pcsm,
    CallingConvention = CallingConvention.StdCall,
    CharSet = CharSet.Unicode,
    EntryPoint = "PCS")]

And declared the function like:

public static extern int PCSM([MarshalAs(UnmanagedType.BStr)] string AFile);

then in Pascal:

function PCS(AFile: PChar): PChar; stdcall;

var XD: IXMLDocument;
Race: TPCSRace;

begin

try
     if not FileExists(AFile) then
        raise EFOpenError.CreateFmt('File "%s" not found', [AFile]);
     else
         //do something with AFile...

end

but when I call the function like this:

pascalPath = "path\\to\\the\\file";
PCSM(pascalPath);

the Dll doesn't operate on the file (it has to be edited and it is an xml file).

The Dll is officially provided by an organization, so it can't be edited, I've reduced the code, but the Dll is correct.

SOLVED

    [DllImport(pcsm,
        CallingConvention = CallingConvention.Winapi,
        CharSet = CharSet.Ansi,
        EntryPoint = "PCS")]
    public static extern int PCS(string AFile);

and then

        StringBuilder pascalPath = new StringBuilder(xmlPath, xmlPath.Length);

        int result = PCS(pascalPath.ToString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM