how to check the an interface type in c++/cli - c++-cli

i want to convert that line from c# to c++/cli
Idocobj is IPart
IPart is an interface and Idocobj is an object.Are there any way to do this conversion.
i used this code :
Idocobj->GetType() == IPart::typeid
but it dosen't work

You can use dynamic_cast to check for "is". Here is an example:
using namespace System;
namespace NS
{
public interface class IFoo
{
void Test();
};
public ref class Foo : public IFoo
{
public: virtual void Test() {}
};
public ref class Bar
{
public: virtual void Test() {}
};
}
template<class T, class U>
bool isinst(U u) {
return dynamic_cast< T >(u) != nullptr;
}
int main()
{
NS::Foo^ f = gcnew NS::Foo();
NS::Bar^ b = gcnew NS::Bar();
if (isinst<NS::IFoo^>(f))
Console::WriteLine("f is IFoo");
if (isinst<NS::IFoo^>(b) == false)
Console::WriteLine("f is not IFoo");
Console::ReadKey();
}
But normally, you never use "is".... you always want to do something with the check... so normally you should use "as" which directly mapps to dynamic_cast:
NS::IFoo^ ifoo = dynamic_cast<NS::IFoo^>(f);
if (ifoo != nullptr)
{
// Do something...
ifoo->Test();
}

Related

Mockito mock with constructor parameter

I am using mockito 1.9.5 and wanting to test a class that i have posted on github.
The issue is that I need to mock the getStringFromExternalSources method.
MyClass code:
public class MyClass {
String a,b,c;
public MyClass(String a, String b, String c) {
this.a = a;
this.b = b;
this.c = c;
}
public String executeLogic (String d) {
return a + b + c + d;
}
public String getStringFromExternalSources (){
return "i got it from some place else";
}
}
My current test:
#RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
#Test
public void MyClassTest() {
MyClass mc = Mockito.spy(new MyClass("a","b","c") );
Mockito.doReturn("mock").when(mc.executeLogic("real"));
Mockito.doReturn("externalString").when(mc.getStringFromExternalSources());
System.out.println(mc.executeLogic("real"));
}
}
Any pointers ?
You can mock any method using when().thenReturn() construct.
Example:
MyClass mc = Mockito.spy(new MyClass("a","b","c"));
when(mc.getStringFromExternalSource()).thenReturn("I got it from there!!");
So whenever the method 'getStringFromExternalSource()' is invoked for the mocked object mc then it will return "I got it from there!!".
if you want to Test class with different parameters then you can use #Parameters annotation to provide parameters to the class in conjunction with Parameterized runner and mention the parameters in a public static method with #Paramters annotation. A rough example would be:
#RunWith(Parameterized.class)
class SomeTestClass{
#Mock
SomeTestClass mSomeTestClassInstance;
#Parameters
public static Object provideParameters() {
Object[] objects = new Object[]{
0,
0,
2
};
return objects;
}
public SomeTestClass(Object argument1){
mArgument1 = argument1;
}
#Test
public void testSomeMethod{
Object returnValue = mSomeTestClassInstance.testSomeMethod(mArgument1);
assertequals(mArgument1,returnValue)
}
}
How to mock getStringFromExternalSources method:
public class MyClassTest {
#Test
public void MyClassTest() {
MyClass mc = mock(MyClass.class);
when(mc.executeLogic("real").thenReturn("mock");
when(mc.getStringFromExternalSources().thenReturn("externalString");
System.out.println(mc.executeLogic("real"));
}
}

How to use JMockit MockUp for default interface method

Trying to apply a MockUp on a Java 8 default interface method, and JMockit tells me that method cannot be found. This has been tried with JMockit 1.15, 1.19, and 1.25. Here's a very simple use case:
#RunWith(JMockit.class)
public class TestTest {
public interface MyInterface {
default void foo(int f) {
bar(String.valueOf(f));
}
void bar(String s);
}
public class MyClass implements MyInterface {
public void bar(String s) {
System.out.println(s);
}
}
#Test
public void testtest() throws Exception {
new MockUp<MyClass>() {
#Mock
void foo(int i) {
System.out.println("MOCKMOCK " + (i*2));
}
#Mock
void bar(String s) {
System.out.println("MOCK " + s);
}
};
MyClass baz = new MyClass();
baz.foo(5);
baz.bar("Hello world");
}
}
This gets me the error
java.lang.IllegalArgumentException: Matching real methods not found for the following mocks:
com.example.dcsohl.TestTest$1#foo(int)
at com.example.dcsohl.TestTest$1.<init>(TestTest.java:29)
at com.example.dcsohl.TestTest.testtest(TestTest.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
...
How can we #Mock this method?
Slightly modifying your use case to return strings instead of printing to standard out the following solution will work.
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import mockit.Expectations;
public class TestTest {
public interface MyInterface {
default String foo(int f) {
return bar(String.valueOf(f));
}
String bar(String s);
}
public class MyClass implements MyInterface {
public String bar(String s) {
return s;
}
}
#Test
public void testtest() throws Exception {
MyClass baz = new MyClass();
new Expectations(MyClass.class) {{
baz.foo(anyInt); result = "FOOMOCK";
baz.bar(anyString); result = "BARMOCK";
}};
assertEquals(baz.foo(5), "FOOMOCK");
assertEquals(baz.bar("Hello world"), "BARMOCK");
}
}
There are many useful examples of how to mock out interfaces with method bodies (ie default or static methods) outlined in the examples section on the jmockit github repository.
Use #Mocked instead of a MockUp, it supports default methods.

Tweak jackson polymorphic deserialization

I have a simple polymorphic model like this
public class Foo {
private Bar bar1;
private Bar bar2;
public Bar getBar1() {
return bar1;
}
public Bar getBar2() {
return bar2;
}
public void setBar1(Bar bar1) {
this.bar1 = bar1;
}
public void setBar2(Bar bar2) {
this.bar2 = bar2;
}
}
#JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "#type")
public class Bar {
}
public class BarExpression extends Bar {
private String expression;
public String getExpression() {
return expression;
}
#JsonIgnore
public Object getValue() {
return null;
}
public void setExpression(String expression) {
this.expression = expression;
}
}
public class BarLiteral extends Bar {
private String value;
private String type;
public String getType() {
return type;
}
public Object getValue() {
return value;
}
public void setType(String type) {
this.type = type;
}
public void setValue(String value) {
this.value = value;
}
}
Serializing a simple example like this
public void run() throws Exception {
Foo foo;
BarLiteral bar1;
BarExpression bar2;
//
foo = new Foo();
bar1 = new BarLiteral();
bar1.setType("java.lang.String");
bar1.setValue("gnu");
foo.setBar1(bar1);
bar2 = new BarExpression();
bar2.setExpression("bean.property * 2");
foo.setBar2(bar2);
//
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
StringWriter w = new StringWriter();
mapper.writeValue(w, foo);
System.out.println(w.toString());
}
gives the expected result:
{
"bar1" : {
"#type" : "de.mit.jackson.BarLiteral",
"value" : "gnu",
"type" : "java.lang.String"
},
"bar2" : {
"#type" : "de.mit.jackson.BarExpression",
"expression" : "bean.property * 2"
}
}
The question is now: I want to improve user experience when handwriting this "DSL" by supporting "primitive shortcuts" for the typed "Bar..." classes like this
{
"bar1" : "gnu",
"bar2" : "#{bean.property * 2}"
}
The solution that came closest was using a converter on Foo#bar1 and Foo#bar2, checking for either String or "Bar" input, but this solution requires decoration of every attribute definition.
Creating a deserializer with a comparable behavior did not work, as the #JsonTypeInfo is not compatible in the sense that i can have a #JsonDeserialize implementation that will check for a String event and then delegate to the standard #JsonTypeInfo process. The #JsonTypeInfo standard will check only for the #type and then delegate back to the (subtype) deserializer which is again my wrapper implementation.
The required process is
if input event is string {
parse and return string input
} else {
activate #type parsing delegate;
after #type parsing activate standard BeanDeserializer
(**not** my implementation)
}
Is there another hook i am missing?

Return string from c++ function pointer invoked from c#

I need to call a c++ callback function from c# that returns a String. When I try with the code below the application crashes hard (with a message saying that it may be due to a corruption of the heap).
Here's the c++ code:
static String^ CppFunctionThatReturnsString()
{
return gcnew String("From C++");
}
void main()
{
CSharp::CSharpFunction(IntPtr(CppFunctionThatReturnsString));
}
And here's the c# code:
public class CSharp
{
private delegate string CppFuncDelegate();
public static void CSharpFunction(IntPtr cppFunc)
{
var func = (CppFuncDelegate)Marshal.GetDelegateForFunctionPointer(cppFunc, typeof(CppFuncDelegate));
func(); // Crash
}
}
Do I have to do some kind of marshaling magic with the string before returning it?
Why are you using function pointers in the first place? Just pass an instance of the delegate to the C# code:
C++:
static String^ CppFunctionThatReturnsString()
{
return gcnew String("From C++");
}
void main()
{
CSharp::CSharpFunction(new CSharp::CppFuncDelegate(CppFuncThatReturnsString));
}
C#:
public class CSharp
{
private delegate string CppFuncDelegate();
public static void CSharpFunction(CppFuncDelegate d)
{
d();
}
}
I think you may need to put CppFuncThatReturnsString inside a class.
I found the answer on this ten year old page.
c++:
static const char* __stdcall CppFunctionThatReturnsString()
{
return "From C++";
}
void main()
{
CSharp::CSharpFunction(IntPtr(CppFunctionThatReturnsString));
}
c#:
public class CSharp
{
private delegate IntPtr CppFuncDelegate();
public static void CSharpFunction(IntPtr cppFunc)
{
var func = (CppFuncDelegate)Marshal.GetDelegateForFunctionPointer(cppFunc, typeof(CppFuncDelegate));
Marshal.PtrToStringAnsi(func());
}
}
That is, pass it as an IntPtr and marshal it into a string on the C# side.

Problem with design in OOP (Virtual member call in constructor)

I am trying to achieve something like the following:
class Foo
{
public virtual int Number { get; set; }
public Foo(int n)
{
Number = n; //Virtual member call in constructor
}
public void Do() {
Console.WriteLine(Number);
}
}
class Bar : Foo
{
public override int Number
{
get
{
return x.Val;
}
set
{
x.Val = value;
}
}
Bar(int n) : base(n)
{
X x = new X();
x.Val = n;
}
public void F() {
x.Something(); //changes x.Val
}
}
The reason I am doing this is because I need to propagate the call to Do when called from a variable of type Bar.
Now, I can have objects that either inherit from Foo or Bar, thus Number needs to be the way it is now, ie directly expose the Val property of x. This is because I need to allow for the following code:
Bar b = new Bar(5);
b.F(); //changes the value of Val in x
b.Do(); //Needs to print the correct, modified value
The problem here is obviously in Foo, when assigning n to Number (Virtual member call in constructor) since x from the subclass would not have been initialized yet.
What do you think is a better way to structure such a design?
I can't use this current code because I am calling a virtual member from the constructor, which causes the Object Reference not set to an Instance of an Object exception since x in Number from Bar would not have been yet initialized.
My favorite quote:
Favor composition over inheritance
I would separate underlying data from operations:
interface IMyNumber
{
int Number { get; set; }
void Something();
}
class MyNumber : IMyNumber
{
public int Number { get; set; }
public MyNumber(int n)
{
Number = n;
}
void Something() {... }
}
class MyBoxedNumber : IMyNumber
{
int Number { get { ... } set {... } }
void Something() {... }
}
class Bar
{
private IMyNumber_foo;
Bar(IMyNumber foo)
{
_foo = foo;
}
public void F() {
_foo.Something(); //changes x.Val
}
public void Do() {
Console.WriteLine(...)
}
}