开发者

C# dll call not passing char* to C++ MFC regular dll

I have a C++ MFC regular DLL I am calling with the following:

public static class Access3rdPartyDLL
{
  public static string FilePath;
  [DllImport("3rdparty.dll")]  
  // I have also tried LPWStr
  public static extern long Download([开发者_JAVA技巧MarshalAs(UnmanagedType.LPStr)]string sDownloadFile,
                                   int iDeviceNum
                                   ...);

  public static long DownloadToDevice()
  {
    long result;
    string FilePath = "C:\\myfile.txt"
    result = Download(FilePath, 1, ...);
    // check if success or error
    if(result > 0)
    ...
  }
}

I get an error back from the DLL saying "File: 'C:\myfile.txt' not found. But its there...

I have also tried using StringBuilder but this also fails.

Could this be a problem with the DLL or am I doing something wrong?

I found this current code here: SO: equivalent char* in C#

EDIT: I have done this in C++ before and this code works:

extern "C" __declspec(dllimport) HRESULT __stdcall Download(char* sDownloadFile, int ...  

which I call with:

HRESULT result = Download(file_for_download, 1, .. // where file_for_download is a char*


The only thing wrong with the P/invoke is that you are using C# long which is 64 bits, but an HRESULT is only 32 bits.

You have matching calling conventions, default marshalling for managed string is char* on the unmanaged side.

Mismatching return value size would not explain why your C# code receives a string message File: 'C:\myfile.txt' not found so your main problem most likely lies in the code that you haven't shown us.


I don't see any reason why the following wouldn't work in this simple scenario:

[DllImport( "3rdparty.dll", CharSet = CharSet.Ansi )]
static extern long Download(string sDownloadFile, int iDeviceNum, ...)

long result = Download("C:\\myfile.txt", 1, ...);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜