Tuesday, July 31, 2007

.NET Interop: Calling Managed from Unmanaged

I ran into another issue today when dealing with .NET Interop. This particular case had to do with invoking an unmanaged export. The exception happened on the .NET side but we never got to the exported method. To make a long story short the problem was the floating point control word wasn't set to what .NET expects. I have found this wasn't much of a problem with .NET 1.0 or 1.1 so something has obviously changed in .NET 2.0.

The moral of the story is to wrap every single one of your interop calls with this pattern:


var
SavedCW: Word;
begin
SavedCW := Get8087CW;
try
Set8087CW($027f);
// ToDo: Insert your interop code here.
finally
Set8087CW(SavedCW);
end;
end.

2 comments:

Anonymous said...

Shouldn't it be $37F ? That is the control word that Windows "sets" before starting the application.

Chris Bensen said...

Andreas,

I honestly can't recall off the top of my head, but I do know that .NET uses $27f.

Post a Comment