Monday, 15 September 2014

interop - Consuming native C++ (compiled with /CLR) in C#: why does it pretend to work? -



interop - Consuming native C++ (compiled with /CLR) in C#: why does it pretend to work? -

i have body of 'normal' c++ code i'm trying create usable c# client. have compiled /clr. know isn't enough: have introduce managed wrapper classes ("ref") create code callable managed code. question happened before introduced ref classes.

i found native c++ classes visible c# project, , write

mynativeclass mnc = new mynativeclass();

... although effort phone call method on instance rejected compiler. found when ran c# code, mynativeclass constructor never called - indeed effort instantiate mnc seemed produce no code @ all, completed without error.

how c# interpreting native types in project? why did compiler apparently allow me instantiate instance? why methods treated differently types themselves?

you made 2 mistakes create code work. first declared c++ class public, this:

public class mynativeclass {};

this not syntax makes sense in c++ allowed c++/cli compiler. omitting public have produced error message in c# code, cs0122: "foo inaccessible due protection level".

second error compiled native c++ class /clr in effect. works fine, c++03 compliant code can compiled il , gets just-in-time compiled machine code jitter, managed code. , executes fine well. not efficient so, lost advantage of having compile-time optimizer available produce best possible code. still gets optimized, jitter doesn't have same luxury of time available job c++ code optimizer can do. avoid moving c++ code in separate source code file can compile without /clr in effect. or using #pragma managed in source code.

anyhoo, ended assembly indeed contains declaration mynativeclass managed compiler can see. can see running ildasm.exe on assembly. you'll see gets embedded value type type. blob of bytes no constructor , no methods. decent match c++ object managed point of view, bytes can stored anywhere value type can stored. declaring variable of type in c# works doesn't useful, creates blob bytes set 0. possible utilize of declaration can declare typed pointer class , pass around, that's all.

interop c++-cli

No comments:

Post a Comment