C++ / CLI cannot access protected member of base class - c++-cli

I have this class:
ref class Wrapper {
protected:
Native *pn;
public:
Wrapper(int val) { pn = new Native( val ); }
};
Then I derive from it:
ref class DerivedWrapper : public Wrapper{
public:
DerivedWrapper(int val) {pn = new DerivedNative(val); }
}
The compiler complains:
error C2248 ‘ Wrapper::pn’ : cannot access private member declared in class ‘Wrapper’
The base class native pointer is clearly protected, and the derived class should have ready access to it. All my instincts tell me this should work. Is there something peculiar to ref classes?
I’m compiling with VS 2008 SP 1

The native type in your case has to have public or protected accessibility in the compiled assembly itself. There is a special make_public pragma directive that can promote the native type. Add this to the code:
#pragma make_public(Native)
The make_public pragma is documented at http://msdn.microsoft.com/en-us/library/ms235607.aspx

Consider initializing pn in a constructor of Wrapper, or you need to provide default constructor for your Wrapper. Don't forget 'public' in the ref class definition.
public ref class Wrapper {
protected:
Native *pn;
Wrapper(Native * fpn):pn(fpn)
{}
public:
Wrapper(int val) { pn = new Native( val ); }
};
ref class DerivedWrapper : public Wrapper{
public:
DerivedWrapper(int val):Wrapper(new DerivedNative(val)){}
};

Related

unmapped target property and mapstruct calls constructor with null parameter

I'm exploring mapstruct to map JPA entities and DTO objects. Entities and DTOs have abstract base classes that contain id and version fields that I'd like to keep private so that they can not be modified (public getter, no setter for both types). I made a most simple reproducer to demonstrate the idea. Abstract Base class has a private field name. To copy the field values back and forth Base defines a constructor that has a Base parameter. The constructor picks the private field from the parameter and assigns it to it's own private field:
package de.ruu.lab.map.read_only_field_in_base;
public abstract class Base
{
private String name;
public Base(String name) { this.name = name; }
protected Base(Base source) { name = source.name; }
public String getName() { return name; }
}
These are the subclasses of Base:
package de.ruu.lab.map.read_only_field_in_base;
import de.ruu.lab.map.read_only_field_in_base.SimpleMapper.Default;
public class Source extends Base
{
public Source(String name) { super(name); }
#Default
public Source(Base base) { super(base); }
}
package de.ruu.lab.map.read_only_field_in_base;
import de.ruu.lab.map.read_only_field_in_base.SimpleMapper.Default;
public class Target extends Base
{
public Target(String name) { super(name); }
#Default
public Target(Base base) { super(base); }
}
I have to annotate the default constructor to resolve constructor ambiguity for mapstruct. The mapper looks like this:
package de.ruu.lab.map.read_only_field_in_base;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.RetentionPolicy.CLASS;
import java.lang.annotation.Retention;
import org.mapstruct.Mapper;
import org.mapstruct.Qualifier;
import org.mapstruct.factory.Mappers;
#Mapper
public interface SimpleMapper
{
SimpleMapper INSTANCE = Mappers.getMapper(SimpleMapper.class);
Source toSource(Target target);
Target toTarget(Source source);
#Qualifier // make sure that this is the MapStruct qualifier annotation
#java.lang.annotation.Target(CONSTRUCTOR)
#Retention(CLASS)
public #interface Default { }
}
The first problem is that mapstruct warns that there is an unmapped target property "base". What does that mean? Which target property is not mapped? Wouldn't it be possible to print the name of the property in the warning? I use eclipse as IDE, maybe the behaviour is different with other tools?
I tried annotating the mapping methods with
#Mapping(target="name", ignore = true)
but that does not let the warning disappear.
Because mapstruct just makes a warning I hoped everything would be ok and I created a tiny test class:
package de.ruu.lab.map.read_only_field_in_base;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import org.junit.jupiter.api.Test;
class SimpleMapperTest
{
#Test void shouldMapSourceToTarget()
{
Source source = new Source("map me");
Target target = SimpleMapper.INSTANCE.toTarget(source);
assertThat(target.getName(), is(source.getName()));
}
#Test void shouldMapTargetToSource()
{
Target target = new Target("map me");
Source source = SimpleMapper.INSTANCE.toSource(target);
assertThat(source.getName(), is(target.getName()));
}
}
Both tests fail with a NPE because of some strange code mapstruct generated:
package de.ruu.lab.map.read_only_field_in_base;
import javax.annotation.processing.Generated;
#Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2022-09-18T11:08:20+0200",
comments = "version: 1.5.2.Final, compiler: Eclipse JDT (IDE) 1.4.200.v20220802-0458, environment: Java 17.0.2 (GraalVM Community)"
)
public class SimpleMapperImpl implements SimpleMapper {
#Override
public Source toSource(Target target) {
if ( target == null ) {
return null;
}
Base base = null;
Source source = new Source( base );
return source;
}
#Override
public Target toTarget(Source source) {
if ( source == null ) {
return null;
}
Base base = null;
Target target = new Target( base );
return target;
}
}
Obviously code like this causes the NPE:
Base base = null;
Source source = new Source( base );
IMO this would be correct ("target" is the name of the method's parameter):
Source source = new Source( target );
Maybe this can be solved in an upcoming version. Meanwhile, is there any recommendation how to deal with this now?
Thanks!
The reason why you are getting the warnings is the fact that MapStruct doesn't really care about the private / protected fields you have.
When performing a mapping MapStruct looks at the setters and the constructor parameters to decide which properties need to be mapped.
Looking at your examples you have annotated the constructor that takes Base as a default constructor. This means that from the point of view of MapStruct your objects have properties that are taking Base and thus there is the warning for the unmapped property base.
There are 2 ways that you can do to fix this:
Instruct MapStruct how to map to the base property
#Mapper
public interface SimpleMapper
{
SimpleMapper INSTANCE = Mappers.getMapper(SimpleMapper.class);
#Mapping(target = "base", source = "target")
Source toSource(Target target);
#Mapping(target = "base", source = "source")
Target toTarget(Source source);
}
using the #Mapping you will tell MapStruct that you want to map the source parameters to the base property.
Annotated the constructor with the string a #Default
Instead of annotating the constructor that takes Base as input you can annotate the constructor that takes String as a default constructor.
This way MapStruct will look for how to map a property with the name name and thus will use the public Base#getName method to perform the mapping.
Note: I saw that you have #Qualifier on the #Default annotation, this is not needed. The only requirement for MapStruct for the default annotation is that it needs to be named like that.

Accessing a Kotlin extension function from Java

Is it possible to access extension functions from Java code?
I defined the extension function in a Kotlin file.
package com.test.extensions
import com.test.model.MyModel
/**
*
*/
public fun MyModel.bar(): Int {
return this.name.length()
}
Where MyModel is a (generated) java class. Now, I wanted to access it in my normal java code:
MyModel model = new MyModel();
model.bar();
However, that doesn't work. The IDE won't recognize the bar() method and compilation fails.
What does work is using with a static function from kotlin:
public fun bar(): Int {
return 2*2
}
by using import com.test.extensions.ExtensionsPackage so my IDE seems to be configured correctly.
I searched through the whole Java-interop file from the kotlin docs and also googled a lot, but I couldn't find it.
What am I doing wrong? Is this even possible?
Perhaps like this:
// CallExtensionFunction.java
package com.example.groundup;
public class CallExtensionFunction {
public static void main(String[] args) {
MyModel myModel = new MyModel();
int bar = MyModelKt.bar(myModel);
System.out.println(bar);
}
}
// MyModell.kt
package com.example.groundup
fun MyModel.bar(): Int {
return this.name.length
}
class MyModel() {
val name = "Hugo"
}
The extension function is provided in the corresponding singleton with the suffix "Kt" as a static method.

How to mock a local variable initialized with the member variable

I have two classes Class A and Class SRD (Sample classes for understanding the problem. Real classes are different). Both classes have same Function(method1) with same arguments. Both are not derived from different Classes.
Class SRD is the member of Class A. a function in Class A creates a new object for SRD and calls method1(). It should call the mock function. but it calls the actual implementation
I have Written mock classes for both the classes and defined the mock method in both the classes and Wrote EXPECT_CALL in TEST function
class A{
private:
SRD* srd;
public :
bool Method1();
bool MethodX();
SRD* getsrd() {return srd;}
};
bool A :: MethodX()
{
srd.Method1(); // Not Calling Mock Method - Calling Actual
//Implementation
}
bool A::Method1()
{
....
}
class SRD{
public:
bool Method1();
};
class MockSRD : public SRD{
MOCK_METHOD0(Method1, bool())
};
class MockA : public MockA{
MOCK_METHOD0(Method1, bool())
};
bool SRD::Method1()
{
....
}
class TestA : public A {};
TEST_F(TestA, test1)
{
MockSRD srd;
EXPECT_CALL(srd, Method1())
.Times(testing::AnyNumber())
.WillRepeatedly(Return(true));
srd.Method1() //Working fine - Caling mock Method;
MethodX()
}
When i call s1.Method1(), It should call the mock method. how should i do that ?
I don't want to change the production code.
Thanks for taking time to respond the Question . #Chris Oslen & #sklott
I forgot to make the base class method to Virtual. Its worked fine when i change the base class methods

Limit allowed COM Interfaces by using template function with limited variadic parameters (std::is_same)

I have wrapper classes contaning COM pointers (or smart pointers) to different interfaces.
INTEND:
Some COM classes can be obtained from various other COM interfaces, and I want to make a template constructor with variadic types, which would allow passing arguments only of appropriate types.
something like:
template <class T, class = typename
std::enable_if<std::is_base_of<IUnknown, T>::value>::type, class ... Types>
class WithCOMptrbase
{
protected:
T* ptr_;
public:
//construct smart pointer by copy
WithCOMptrbase(T* ptr, bool AddRef = false)
: ptr_(ptr)
{
if (AddRef) ptr_->AddRef();
}
/*construct a smart pointer by querying an interface from an argument of
a type which is the same as one of the variadics*/
template <class TypeOther, class = typename
std::enable_if<syd::is_same<Types... , TypeOther>::value... ||
...>::type> /*there needs to be a proper version*/
WithCOMptrbase(TypeOther* ptr)
: ptr_(cQueryInterface<T>(ptr))
{}
//other methods
};
helper function:
template <class U, class = typename
std::enable_if<std::is_base_of<IUnknown, U>::value>::type>
T* cQueryInterface<T>(U *ptr)
{
T* out;
HRESULT hr = ptr->QueryInterface(__uuidof(T), (void**)&out);
if (!SUCCEEED(hr)) throw _com_error(hr);
return out;
}
Therefore, I will define my wrapper class
class WrapperClass : protected WithCOMptrbase<IThis, IInterface1, IInterface2, IInterface3>
{
//methods
};
So far I have found this thread:
How to make a variadic is_same?
but it is only about structs, not functions.
My goal is to limit the possibility of passing inapproprtiate Interface pointer, hence not to deal with wrong interface errors at runtime.
UPDATE:
Since Composition is preferable over inheritance, I've done some rethinking and decided to use a template function rather than a template class. So far I've managed to combine given answers and came up with this:
template <bool S, class Out, class Other, typename
std::enable_if<S>::type* = nullptr>
//copy-construct Smart Pointer for same Interfaces
WComPtr<Out> WFilterSame(const WComPtr<Other>& pOther)
{
return WComPtr<Out>(pOther);
}
template <bool S, class Out, class Other, typename
std::enable_if<!S>::type* = nullptr>
//Query Interface if differ
WComPtr<Out> WFilterSame(const WComPtr<Other>& pOther)
{
return pOther.QueryInterface<Out>();
}
template <class Out, class ... Permitted, class Other>
WComPtr<Out> WFilterComInterfPtr(const WComPtr<Other>& pOther)
{
static_assert(std::is_same<Out, Other>::value ||
(std::is_same<Permitted, Other>::value || ...),
"Interface is not supported.");
return WFilterSame<std::is_same<Out, Other>::value, Out>(pOther);
}
Now I can define a constructor of my COM wrapper class:
class WComClass
{
private:
WComPtr<Interface> pComPtr_; //My Smart COM pointer
template <class Other>
WComPtr<Interface> WFilter(const WComPtr<Other>& pOther)
{
return WFilterComInterfPtr<Interface, IAllowed1, IAllowed2>(pOther);
}
public:
template <class Other>
WComClass(const WComPtr<Other>& pOther)
: pComPtr_(WFilter(pOther))
{}
//methods
};
So far it behaved as intended (WFilterComInterfPtr), I don't expect it to fail in the wrapper class costructor.
Try with
template <class TypeOther, class =
std::enable_if_t<(std::is_same_v<Types, TypeOther> || ...)>>
WithCOMptrbase(TypeOther* ptr)
: ptr_(cQueryInterface<T>(ptr))
{}
I mean... you're using three ellipsis instead of one (remove the ellipsis after ::value and the one after Types) and you need an additional couple of parentheses.
Off topic: are you sure that works
template <class T, class ... Types, class = typename
std::enable_if<std::is_base_of<IUnknown, T>::value>::type>
class WithCOMptrbase
?
SFINAE through a default type after a variadic list?
How about CRTP to avoid some template:
template <typename Base, typename T>
class Impl
{
public:
Impl() = default;
explicit Impl(T*) { static_cast<Base*>(this)->ptr_ = cQueryInterface<T>(ptr); }
};
template <class T, class ... Ts>
class WithCOMptrbase : private Impl<WithCOMptrbase<T, Ts...>, Ts>...
{
static_assert(std::is_base_of<IUnknown, T>::value);
static_assert((std::is_base_of<IUnknown, Ts>::value && ...));
template <typename, typename> friend struct Impl; // We don't have variadic friend :/
protected:
T* ptr_ = nullptr;
public:
using Impl<WithCOMptrbase, Ts>::Impl...;
//construct smart pointer by copy
explicit WithCOMptrbase(T* ptr, bool AddRef = false) : ptr_(ptr)
{
if (AddRef) ptr_->AddRef();
}
//other methods
};

Static data in Kotlin

Please tell me, is there any difference (in terms of Java) in this examples:
object DefaultValues {
val FILES_TO_DOWNLOAD = 100
}
and
class DefaultValues {
companion object {
val FILES_TO_DOWNLOAD = 100
}
}
Without class or object wrapper:
const val DEFAULT_FILES_TO_DOWNLOAD = 100
and
val DEFAULT_FILES_TO_DOWNLOAD = 100
What is the true way to define?:
public static final int FILES_TO_DOWNLOAD = 100
You can use Kotlin bytecode viewer to find out what these options are compiled to.
With Kotlin 1.0.2 the compiled bytecode shows that
val property in object or companion object is compiled into a private static final field inside the class:
// access flags 0x1A
private final static I FILES_TO_DOWNLOAD = 100
and a getter, which is called when referring to the property:
// access flags 0x1019
public final static synthetic access$getFILES_TO_DOWNLOAD$cp()I
From Java, the getter can be called as DefaultValues.INSTANCE.getFILES_TO_DOWNLOAD() or DefaultValues.Companion.getFILES_TO_DOWNLOAD() respectively.
Non-const top level property is compiled to the same to (1) with only difference that the field and getter are placed inside FilenameKt class now.
But top level const val is compiled into a public static final field:
// access flags 0x19
public final static I DEFAULT_FILES_TO_DOWNLOAD = 100
The same public static final field will be produced when a const val is declared inside an object. Also, you can achieve the same resulting bytecode if you add #JvmField annotation to the properties declared in (1).
Concluding that, you can define public static final field using const or #JvmField either in an object or at top level.