Passing native class pointer to another C++/CLI - c++-cli

I have two wrappers written in C++/CLI as followings.
One wrapper get a native class handle and it send this native handle to another class, however, I got a compile error.
I think there are some work-around,
1) #pragme make_public()
2) using IntPtr(sender) and static_cast with IntPtr.ToPointer(receiver).
What is the best solution?
namespace AWrapper {
public ref class AClass
{
public:
NativeClass* GetInfo() { return nativeClass; }
...
private:
NativeClass* nativeClass;
}
namespace BWrapper {
...
void ImageSensor::SetClass(AWrapper::AClass^ aclass)
{
NativeClass* native_tpr;
native_tpr = aclass->GetInfo(); // Not visible, like private
}
}

Related

Mocking and Expecting from a Class instance created using new operator in Google Mock

Need your inputs regarding the below:
I am facing an issue regarding how to write a mock for a base class (StackBT) of which an instance is created in the derived class's constructor (ApplicationBT) that I want to test.
My intention is to write a mock for the StackBT class (Mock_StackBT) and then link this to the unit test so that the instance of the mock is created when doing "new StackBT()" in ApplicationBT's constructor. So that using this I can mock the expectations on StackBT class while testing ApplicationBT class.
out/linux_host/obj/TestApplicationBT.o: In function `TestApplicationBT::SetUp()':
tst/_src/TestApplicationBT.cpp:33: undefined reference to `mockPtr_StackBT'
out/linux_host/lib/libServer.a(ApplicationBT.o): In function `ApplicationBT::init()':
/_src/ApplicationBT.cpp:36: undefined reference to `StackBT::registerCallbacks()'
/_src/ApplicationBT.cpp:43: undefined reference to `StackBT::sendBTMacAddress(std::string)'
collect2: error: ld returned 1 exit status
make: *** [out/linux_host/bin/Test] Error 1
I get the above compiler error while compiling the below code snippet:
StackBT.h:
class StackBT
{
StackBT(){}
void registerCallbacks();
void sendBTMacAddress(std::string str);
}
Mock_StackBT.h:
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include <string>
using ::testing::NiceMock;
class Mock_StackBT;
extern NiceMock < Mock_StackBT >* mockPtr_StackBT;
class Mock_StackBT: public StackBT
{
Mock_StackBT(){}
MOCK_METHOD0(registerCallbacks, void());
MOCK_METHOD1(sendBTMacAddress, void(std::string str));
}
Mock_StackBT.cpp:
#include "Mock_StackBT.h"
NiceMock < Mock_StackBT >* mockPtr_StackBT;
void registerCallbacks()
{
mockPtr_StackBT->registerCallbacks();
}
void sendBTMacAddress(std::string str)
{
mockPtr_StackBT->sendBTMacAddress(std::string str);
}
ApplicationBT.h:
class ApplicationBT
{
public:
ApplicationBT() : mpoStackBT(new StackBT())
void init()
{
mpoStackBT->registerCallbacks();
mpoStackBT->sendBTMacAddress("AB:CD:EF:GH:IJ:KL");
}
friend class TestApplicationBT;
scoped_ptr<StackBT> mpoStackBT;
}
TestApplicationBT.h
class TestApplicationBT : public ::testing::Test
{
protected:
virtual void SetUp ()
{
mockPtr_StackBT = &stackBTMock;
ptrApplicationBT = new ApplicationBT();
}
void TearDown()
{
delete ptrApplicationBT;
}
public:
TestApplicationBT ()
{
}
~TestApplicationBT ()
{
ptrApplicationBT = NULL;
}
scoped_ptr<ApplicationBT> ptrApplicationBT;
StackBT* ptrStackBT;
NiceMock<Mock_StackBT> stackBTMock;
};
TEST_F(TestApplicationBT, Init)
{
EXPECT_CALL(stackBTMock, registerCallbacks() ).Times(1);
EXPECT_CALL(stackBTMock, sendBTMacAddress(_) ).Times(1);
ptrApplicationBT->init();
}
First problem is that you are using mockPtr_StackBT in TestApplicationBT.cpp, but it is defined in
Mock_StackBT.cpp. The second issue is that the call to ApplicationBT::init method calls functions
registerCallbacks and sendBTMacAddress through pointer mpoStackBT, but if you look closely at
the constructor for class ApplicationBT you will se that this pointer is set to an object of class StackBT
and not Mock_StackBT. This causes a linker error because you did not implement functions
registerCallbacks and sendBTMacAddress for class StackBT, you have only declared them.
The main problem is that you are not swapping your real implementation with a mock, your approach is
not correct. First of all, you are not suppossed to create implementations for functions registerCallbacks
and sendBTMacAddress in the mock class, googlemock does that for you (file Mock_StackBT.cpp is completely
unnecessary). Also, you need a common interface for classes StackBT and Mock_StackBT so you can
switch implementations. Here is how you do it:
Create interface:
class IStackBT
{
public:
virtual IStackBT() {}
virtual void registerCallbacks() = 0;
virtual sendBTMacAddress(std::string str) = 0;
}
Create class for production:
class StackBT : public IStackBT
{
public:
void registerCallbacks() override
{
// Your code that registers callbacks
}
void sendBTMacAddress(std::string str) override
{
// Your code that sends mac address
}
}
Create mock class:
class StackBTMock : public IStackBT
{
public:
MOCK_METHOD0(registerCallbacks, void());
MOCK_METHOD1(sendBTMacAddress, void(std::string str));
}
Now, make your class ApplicationBT hold a IStackBT pointer and use some form of factory method
to create a real or mock object, depending on the fact if you are building unit test or deployment code. There
are several ways, here is how I did it on my gmock project. Create a preprocessor define for your unit testing
project that indicates the code is built for unit tests. If it is, for example, named MY_UNIT_TESTS, then in
constructor of ApplicationBT do the following:
ApplicationBT() : mpoStackBT(createStackBT())
where createStackBT is a function defined as:
IStackBT * createStackBT()
{
#ifdef MY_UNIT_TESTS
return new StackBTMock;
#else
return new StackBT;
#endif
}
This will perform the swapping of implementation during compilation time when you are building your unit test executable. Since you will be performing this swapping on several classes as you write more tests, I suggest that you wrap the factory functions in some class that provides the desired implementations (mock or production) of your classed. For instance, my project has a class named ImplementationProvider that performs this task.

AspectJ, Intertype Definition

I am receiving this error when I compile
The type XXX must implement the inherited abstract method
I have three files
A default implementation [com.SafeReaderIMPL.java]
public class SafeReaderIMPL implements ISafeReader {
private boolean successfulRead;
public SafeReaderIMPL() {
successfulRead = true;
}
protected void fail() {
successfulRead = false;
}
#Override
public boolean isSuccessfulRead() {
return successfulRead;
}
}
An interface file [com.ISafeReader.java]
public interface ISafeReader {
public boolean isSuccessfulRead();
}
An apsect (using annotations) [com.SafeReaderAspect.java]
#Aspect
public class SafeReaderAspect {
#DeclareParents(value = "com.BadReader", defaultImpl = SafeReaderIMPL.class)
public ISafeReader implementedInterface;
#AfterThrowing(pointcut = "execution(* *.*(..)) && this(m)", throwing = "e")
public void handleBadRead(JoinPoint joinPoint, ISafeReader m, Throwable e) {
((SafeReaderIMPL)m).fail();
}
}
And a Test Class [com.BadReader]
public class BadReader {
public void fail() throws Throwable {
throw new Throwable();
}
}
I compile the first three files in a separate jar using
ajc -source 1.8 -sourceroots . -outjar aspectLib.jar
I then compile the second file using the aspectLib like so
ajc -source 1.8 -sourceroots . -aspectpath ./aspectLib.jar -outjar common.jar
When I go to compile the second jar I get the error. I am using the latest stable version of AspectJ 1.8.3
BadReader.java:10 [error] The type BadReader must implement the
inherited abstract method ISafeReader.isSuccessfulRead() public class
BadReader {
^^^^^^^^
The problem is not two-step compilation as such, but the fact that #DeclareParents in #AspectJ syntax in not 100% compatible with declare parents in native syntax. Actually, #DeclareParents for introducing default interface implementations is superseded by #DeclareMixin (see this bug ticket), but the downside of the mixin approach is that you do not have a real A implements B scenario there, i.e. you cannot cast as you wish in your after-throwing advice, so this is also not a good option in your case.
So what do you do if you want to keep the two-step compilation approach? Just use native syntax:
Interface:
package com;
public interface ISafeReader {
boolean isSuccessfulRead();
}
Default implementation:
package com;
public class SafeReaderIMPL implements ISafeReader {
private boolean successfulRead;
public SafeReaderIMPL() { successfulRead = true; }
public void fail() { successfulRead = false; }
#Override public boolean isSuccessfulRead() { return successfulRead; }
}
ITD aspect:
package com;
public aspect SafeReaderAspect {
declare parents : com.BadReader implements SafeReaderIMPL;
after(ISafeReader safeReader) throwing : execution(* *(..)) && this(safeReader) {
System.out.println(thisJoinPoint + " - calling 'fail()' before rethrowing error");
((SafeReaderIMPL) safeReader).fail();
}
}
ITD target class with sample main method:
package com;
public class BadReader {
public void doSomething() {
throw new RuntimeException("my error");
}
public static void main(String[] args) {
BadReader badReader = new BadReader();
System.out.println("badReader.isSuccessfulRead() = " + badReader.isSuccessfulRead());
try { badReader.doSomething(); }
catch(Throwable t) { System.out.println(t); }
System.out.println("badReader.isSuccessfulRead() = " + badReader.isSuccessfulRead());
}
}
Now you can use the two-stage compilation approach.
Console output:
badReader.isSuccessfulRead() = true
execution(void com.BadReader.doSomething()) - calling 'fail()' before rethrowing error
java.lang.RuntimeException: my error
badReader.isSuccessfulRead() = false
The problem is due to the two-step compilation. During the second step, ajc needs the source code of SafeReaderIMPL to be able to weave BadReader, but it cannot find it into aspectLib.jar
In fact, if you try compiling in a single step (I did), it compiles and runs.
Unfortunately I don't know a way to fix this without providing the source code during the second compile step, which I suppose would render the whole two-step approach a bit pointless.

Accesing arraylist property from another class using constructor

So i have a class that makes an array list for me and i need to access it in another class through a constructor but i don't know what to put into the constructor because all my methods in that class are just for manipulating that list. im either getting a null pointer exception or a out of bounds exception. ive tried just leaving the constructor empty but that dosent seem to help. thanks in advance. i would show you code but my professor is very strict on academic dishonesty so i cant sorry if that makes it hard.
You are confusing the main question, with a potential solution.
Main Question:
I have a class ArrayListOwnerClass with an enclosed arraylist property or field.
How should another class ArrayListFriendClass access that property.
Potential Solution:
Should I pass the arraylist from ArrayListOwnerClass to ArrayListFriendClass,
in the ArrayListFriendClass constructor ?
It depends on what the second class does with the arraylist.
Instead of passing the list thru the constructor, you may add functions to read or change, as public, the elements of the hidden internal arraylist.
Note: You did not specify a programming language. I'll use C#, altought Java, C++, or similar O.O.P. could be used, instead.
public class ArrayListOwnerClass
{
protected int F_Length;
protected ArrayList F_List;
public ArrayListOwnerClass(int ALength)
{
this.F_Length = ALength;
this.F_List = new ArrayList(ALength);
// ...
} // ArrayListOwnerClass(...)
public int Length()
{
return this.F_Length;
} // int Length(...)
public object getAt(int AIndex)
{
return this.F_List[AIndex];
} // object getAt(...)
public void setAt(int AIndex, object AValue)
{
this.F_List[AIndex] = AValue;
} // void setAt(...)
public void DoOtherStuff()
{
// ...
} // void DoOtherStuff(...)
// ...
} // class ArrayListOwnerClass
public class ArrayListFriendClass
{
public void UseArrayList(ArrayListOwnerClass AListOwner)
{
bool CanContinue =
(AListOwner != null) && (AListOwner.Length() > 0);
if (CanContinue)
{
int AItem = AListOwner.getAt(5);
DoSomethingWith(Item);
} // if (CanContinue)
} // void UseArrayList(...)
public void AlsoDoesOtherStuff()
{
// ...
} // void AlsoDoesOtherStuff(...)
// ...
} // class ArrayListFriendClass
Note, that I could use an indexed property.

C++ CLI Wrapper

I’ve a question about creating a C++ CLI Wrapper for a native C++ class to be used in C#.
Here is an example code:
#include "stdafx.h"
#pragma once
using namespace System;
namespace Wrapper {
class NativeClass
{
public:
NativeClass() {}
int Add(int a, int b)
{
return a+b;
}
};
public ref class Wrapper
{
public:
Wrapper() {pNative = new NativeClass();}
int Add(int a, int b)
{
return(pNative->Add(a,b));
}
~Wrapper()
{
delete pNative;
pNative = 0;
}
!Wrapper()
{
this->~Wrapper();
}
//My problem is here.
NativeClass* GetNative()
{
return pNative;
}
private:
NativeClass* pNative;
};
}
This code works fine. I need to retrieve the pointer that refers the native class to use it in the other wrapper classes. However, I don’t want the function “GetNative” to be visible in C# when I’m using this wrapper class. How can I hide it?
If the other wrapper classes are in the same assembly, make the access internal instead of public. – Roger Rowland Apr 25 '13 at 9:47
.
if they are not in the same assembly? ...
Look into friend assemblies – Sebastian Cabot Feb 1 at 15:43

Rhino.Mocks how to test abstract class method calls

I'm trying to test if the method I want to test calls some external (mock) object properly.
Here is the sample code:
using System;
using Rhino.Mocks;
using NUnit.Framework;
namespace RhinoTests
{
public abstract class BaseWorker
{
public abstract int DoWork(string data);
}
public class MyClass
{
private BaseWorker worker;
public BaseWorker Worker
{
get { return this.worker; }
}
public MyClass(BaseWorker worker)
{
this.worker = worker;
}
public int MethodToTest(string data)
{
return this.Worker.DoWork(data);
}
}
[TestFixture]
public class RhinoTest
{
[Test]
public void TestMyMethod()
{
BaseWorker mock = MockRepository.GenerateMock<BaseWorker>();
MyClass myClass = new MyClass(mock);
string testData = "SomeData";
int expResponse = 10;
//I want to verify, that the method forwards the input to the worker
//and returns the result of the call
Expect.Call(mock.DoWork(testData)).Return(expResponse);
mock.GetMockRepository().ReplayAll();
int realResp = myClass.MethodToTest(testData);
Assert.AreEqual(expResponse, realResp);
}
}
}
When I run this test, I get:
TestCase 'RhinoTests.RhinoTest.TestMyMethod'
failed: System.InvalidOperationException : Invalid call, the last call has been used or no call has been made (make sure that you are calling a virtual (C#) / Overridable (VB) method).
at Rhino.Mocks.LastCall.GetOptions[T]()
at Rhino.Mocks.Expect.Call[T](T ignored)
RhinoTest.cs(48,0): at RhinoTests.RhinoTest.TestMyMethod()
The exception is thrown on the Expect.Call line, before any invocation is made.
How do I approach this - i.e. how to check if the method under test properly forwards the call?
This is .Net 2.0 project (I can no change this for now), so no "x =>" syntax :(
I have to admit, I'm not entirely sure what's going on here, but using Rhino.Mocks 3.6 and the newer syntax, it works fine for me:
[Test]
public void TestMyMethod()
{
MockRepository mocks = new MockRepository();
BaseWorker mock = mocks.StrictMock<BaseWorker>();
MyClass myClass = new MyClass(mock);
string testData = "SomeData";
int expResponse = 10;
using (mocks.Record())
{
//I want to verify, that the method forwards the input to the worker
//and returns the result of the call
Expect.Call(mock.DoWork(testData)).Return(expResponse);
}
using (mocks.Playback())
{
int realResp = myClass.MethodToTest(testData);
Assert.AreEqual(expResponse, realResp);
}
}
It doesn't have anything to do with the Rhino.Mocks version. With the old syntax, I get the same error as you're getting. I didn't spot any obvious errors in your code, but then again, I'm used to this using syntax.
Edit: removed the var keyword, since you're using .NET 2.0.