Why would native code called from .net give different result from calling it from a native program?

妖精的绣舞 提交于 2019-12-03 21:55:51

Wild guess: You marshal a function taking bool to a function taking bool. This gives different results when calling from native code and managed code because bool must not be marshalled to bool

One possibility would be if the native library makes use of native thread local storage. There isn't (necessarily) a one-one mapping between managed threads and native threads.

To eliminate this possibility, you could try wrapping the entire sequence of calls inside calls to BeginThreadAffinity/EndThreadAffinity (that is to say, a single pair of these calls across all calls into the library, not a pair around each individual call into the library)

Key words:

We've written an interop library so that we can use it (native library) from .NET.

This is the source of your errors not the native library. A specific native call (specific function call w/ specific parameters) will return same results no matter how it is called. The issue becomes that your wrapper can introduce subtle bugs where you "think" you are making the same call but the interop version is making a slightly different call (thus different results).

I would start with some very fine unit testing of your interop library at the lowest level. Native function foo(int x, int y). Call it natively, call it via library. Result should be the same. Continue until you find a function call where they are not. If there is a difference than the issue is with your marshalling & interop not the native library. If you find an individual call which returns difference results and you can't find the source of the error in interop then post individual call as a question on SO.

It could be a problem with marshalling / interop as others have suggested.

But it could also be that the native library is making assumptions about its environment that are not expressed only in the call signatures.

There are many ways such assumptions could be made. As a random example, a method in an MFC library that does not call the AFX_MANAGE_STATE macro may be making assumptions that are invalid when being called from .NET code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!