1

I'm calling a C++ DLL from C# via P/Invoke using DllImport. The DLL is produced by a third party and is x86 only (so our C# code is built as x86 as well).

If I call a certain function on the DLL from a console application, I always get one result which is correct. The function takes a file path and extracts some information from the file.

The signature of the function is:

private static extern int Function(
    string str1,
    int bool1,
    ref uint outUint1,
    ref uint outUint2,
    ref uint outUint3,
    ref double outDouble1,
    ref double outDouble2,
    StringBuilder outStr1);

And the unexpected result is in one of the ref uint parameters.

If I create a unit test and call the exact same code (with all parameters and such hardcoded), I get an entirely different result, which is incorrect. The incorrect result is always the same. I've tried both MSTest and NUnit tests using various different runners with the same result.

Cases producing correct results:

  • Console app
  • Winforms app
  • Console app running the code but launched from a Unit Test (NUnit)

Cases producing incorrect results:

  • Test run from Resharper Test Runner (NUnit)
  • Test run from Visual Studio Test Runner (MSTest)
  • Test run from NUnit GUI Test Runner
  • Test run from NUnit Console Test Runner

My test environment is Windows 8 and the C# is built for x86 targeting .NET framework 4.

Do any of you have any ideas about what's causing this issue or what I can do to debug it further?

I will definitely be attempting to contact the third party that created the DLL, but having a good idea about exactly what's causing this issue would substantially increase the chance of it getting resolved.

4

1 回答 1

1

听起来它期望的“文件路径”可能与工作目录相关,或者工作目录甚至应用程序目录对 dll 很重要。

该 dll 也可能尝试引用其目录中的其他 dll,但找不到它们,因为它是从自己的文件夹加载的,而不是在其目录中运行的 exe。

大约在此页面的一半处,它描述了 dll 解析的搜索顺序:

  1. 加载应用程序的目录。

  2. 当前目录。

  3. 系统目录。使用 GetSystemDirectory 函数获取该目录的路径。

  4. 16 位系统目录。没有函数获取这个目录的路径,但是被搜索了。

  5. Windows 目录。使用 GetWindowsDirectory 函数获取该目录的路径。

  6. PATH 环境变量中列出的目录。请注意,这不包括 App Paths 注册表项指定的每个应用程序路径。计算 DLL 搜索路径时不使用 App Paths 键。

希望有帮助。

编辑:另一个想法......您可以为该 DLL 编写一个包装器,以便它返回正确的值,并制作一个与您的单元测试器一起工作的接口,该接口内置到您的包装器中。

于 2012-11-09T20:15:41.363 回答