content inserted into ghashtable being destroyed - gtk

I have a ghashtable object as member of my class. I have created new object of it at constructor. I am calling this function iteratively. When i checked the size of hashtable at each method call it's giving as 0, even if i eep on adding new key-value pairs.
void myFunction(string inString)
{
string val = "some value";
printf("Size:%d",g_hash_table_size(mTable));
g_hash_table_insert(mTable,(void*)inString.c_str(),(void*)val.c_str());
printf("Size:%d",g_hash_table_size(mTable));
}
What could be the reason behind this problem.

The C++ strings are going out of scope and getting destroyed, leaving the hash table with dangling pointers to invalid memory. I don't know if know if that's the only problem in your program but it's a problem visible from looking at the part you posted.

Related

How to make copy of array's elements in the dart

Getting wired issue like main array has been changed if changed value of another array. I think issue is about copying same address, not sure but just thinking of it. I have tried from last 3 hours but unable to get rid from it.
Look at below illustration to get better idea.
List<page> _pageList;
List<page> _orderList = [];
_pageList = _apiResponse.result as List<page>;
_orderList.add(_pageList[0].element);
_orderList[0].title = "XYZ"
//--> Here if I change the `_orderList[0].title` then it also change the `title` inside "_pageList"
How can we prevent the changes in main array?
I got same issue in my one of the project. What I have done is, use json to encode and decode object that help you to make copy of the object so that will not be affected to the main List.
After 3rd line of your code, make changes like below
Elements copyObject = Elements.fromJson(_pageList[0].element.toJson());
// First of all you have to convert your object to the Map and and map to original object like above
_orderList.add(copyObject);
Hope that will help you.
You can use a getter function to create a copy of your list and use that instead of
altering your actual list.
example:
List<Page> get orderList{
return [..._orderList];
}
Lists in Dart store references for complex types, so this is intended behaviour.
From your code:
_orderList.add(_pageList[0].element);
_orderList[0] and _pageList[0].element point to the same reference (if they are non-primitive).
There is no general copy() or clone() method in dart, as far as i know. So you need to copy the object yourself, if you want a separate instance. (see this question)

Cannot create class in AHK after destruction

I'm trying to wrap my head around classes in AHK. I'm C++ dev, so would like to make use of RAII (__New, __Delete), but it looks like I miss some concepts since things look very contra-intuitive for me.
After some tries I came up with this simple example:
class Scenario
{
__New()
{
MsgBox, NEW
}
__Delete()
{
MsgBox, DELETE
}
}
scenario := new Scenario
scenario := new Scenario
scenario := 1
scenario := {}
scenario := new Scenario
Return
As a result I get the following messages:
NEW
NEW
DELETE
DELETE
Questions:
Why doesn't the object get destroyed during the second assignment? I'd assume the number of refs going to 0, no?
How come I get 2 destructions in a row? Where was that object stored meanwhile? How could scenario variable hold both references?
Why was not the third construction called?
Why doesn't the object get destroyed during the second assignment?
Garbage collection had not been triggered yet
I'd assume the number of refs going to 0, no?
References going to 0 does not necessarily trigger GC
How come I get 2 destructions in a row?
Garbage collection cleaned both references at the same time
Where was that object stored meanwhile?
The heap
How could scenario variable hold both references?
scenario does not hold both references
Why was not the third construction called?
Only two Scenario objects are constructed. The variable scenario is a dynamic variable and is not always an instance of the class Scenario. The last assignment scenario := {} just creates an empty object.
Ok, found out what was missing. Two things:
AHK script is case-insensitive.
Since class is an object by itself in AHK it's possible to override the class by another object.
Here is a piece of the documentation:
Because the class is referenced via a variable, the class name cannot be used to both reference the class and create a separate variable (such as to hold an instance of the class) in the same context. For example, box := new Box would replace the class object in Box with an instance of itself. [v1.1.27+]: #Warn ClassOverwrite enables a warning to be shown at load time for each attempt to overwrite a class.
This explains what happened in the code above: variable name scenario is effectively the same as a class name Scenario, so I just quietly overrode my class with an empty object.
Also, since the new instance of the class is created before assignment, I got two 'NEW' in a row, only than 'DELETE'.

Lua light userdata

I have a problem with Lua and I don't know if I going in the right direction. In C++ I have a dictionary that I use to pass parameter to a resource manager. This dictionary is really similar to a map of hash and string.
In Lua I want to access to these resource so I need a representation of hashes. Also hashes must be unique cause are used as index in a table. Our hash function is 64bit and I'm working on 32bit enviroment (PS3).
C++ I have somethings like that:
paramMap.insert(std::make_pair(hash64("vehicleId"), std::string("004")));
resourceManager.createResource(ResourceType("Car"), paramMap);
In Lua want use these resources to create a factory for other userdata.
I do stuff like:
function findBike(carId)
bikeParam = { vehicleId = carId }
return ResourceManager.findResource('car', bikeParam)
end
So, sometime parameter are created by Lua, sometime parameter are created by C++.
Cause my hashkey ('vehicleId') is an index of a table it need to be unique.
I have used lightuserdata to implement uint64_t, but cause I'm in a 32bit enviroment I can't simply store int64 in pointer. :(
I have to create a table to store all int64 used by the program and save a reference in userdata.
void pushUInt64(lua_State *L, GEM::GUInt64 v)
{
Int64Ref::Handle handle = Int64Ref::getInstance().allocateSlot(v);
lua_pushlightuserdata(L, reinterpret_cast<void*>(handle));
luaL_setmetatable(L, s_UInt64LuaName);
}
but userdata are never garbage collected. Then my int64 are never released and my table will grow forever.
Also lightuserdata don't keep reference to metadata so they interfere with other light userdata. Checking the implementation the metadata table is added in L->G_->mt_[2].
doing that
a = createLightUserDataType1()
b = createLightUserDataType2()
a:someFunction()
will use the metatable of b.
I thought that metatable where bounded to type.
I'm pretty confused, with the current implementation lightuserdata have a really limited use case.
With Python you have a hash metafunction that is called anytime the type is used as index for a dictionary. It's possible to do something similar?
Sorry for my english, I'm from Italy. :-/

How to get interpolated message in NHibernate.Validator

I'm trying to integrate NHibernate.Validator with ASP.NET MVC client side validations, and the only problem I found is that I simply can't convert the non-interpolated message to a human-readable one. I thought this would be an easy task, but turned out to be the hardest part of the client-side validation. The main problem is that because it's not server-side, I actually only need the validation attributes that are being used, and I don't actually have an instance or anything else at hand.
Here are some excerpts from what I've been already trying:
// Get the the default Message Interpolator from the Engine
IMessageInterpolator interp = _engine.Interpolator;
if (interp == null)
{
// It is null?? Oh, try to create a new one
interp = new NHibernate.Validator.Interpolator.DefaultMessageInterpolator();
}
// We need an instance of the object that needs to be validated, se we have to create one
object instance = Activator.CreateInstance(Metadata.ContainerType);
// we enumerate all attributes of the property. For example we have found a PatternAttribute
var a = attr as PatternAttribute;
// it seems that the default message interpolator doesn't work, unless initialized
if (interp is NHibernate.Validator.Interpolator.DefaultMessageInterpolator)
{
(interp as NHibernate.Validator.Interpolator.DefaultMessageInterpolator).Initialize(a);
}
// but even after it is initialized the following will throw a NullReferenceException, although all of the parameters are specified, and they are not null (except for the properties of the instance, which are all null, but this can't be changed)
var message = interp.Interpolate(new InterpolationInfo(Metadata.ContainerType, instance, PropertyName, a, interp, a.Message));
I know that the above is a fairly complex code for a seemingly simple question, but I'm still stuck without solution. Is there any way to get the interpolated string out of NHValidator?
Ok, so I know this is an old question, but I stumbled across this when trying to do the same thing, and it helped me get started - so I thought I would provide an answer.
I think the code in the question was on the right track but there are a couple of problems. The interpolator was not completely initialised with the ResourceManager and Culture details, and it doesn't seem to allow for the fact that you can only have one DefaultMessageInterpolator per validation attribute. Also, you don't need an instance of the object you are validating to get an interpolated message.
In the code in the question, where you are initialising the interpolator with the attribute value, you also need to initialise the interpolator with details of the ResourceManager to be used.
This can be done using the overloaded Initialize method on DefaultMessageInterpolator which has the following signature:
public void Initialize(ResourceManager messageBundle,
ResourceManager defaultMessageBundle,
CultureInfo culture)
The first parameter is a user-defined ResourceManager in case you want to use your own resource file for error messages, you can pass a null if you just want to use the default ResouceManager, the second parameter is the default ResourceManager - you can pass
new ResourceManager(
NHibernate.Validator.Cfg.Environment.BaseNameOfMessageResource,
Assembly.GetExecutingAssembly());
for this, the last parameter is the culture to use, (NHibernate.Validator comes with resource files with validation messages in several languages) - if you pass a null in to this it will just use CultureInfo.CurrentCulture
Lastly, you can only have one DefaultMessageInterpolator per attribute, so you will need to create a new DefaultMessageInterpolator for each validation attribute. You could make use of the DefaultMessageInterpolatorAggregator to handle this, or just roll your own.
I hope this helps someone.
Thanks for your help all--I'd upvote if I could. I just wanted to add that in addition to the first Initialize call on the DefaultMessageInterpolator that Stank illustrates, I also had to make a second different Initialize call to fully initialize it (I was getting some Null Reference Exceptions using only the first call). My code is as follows:
string interpolatedMessage = "";
DefaultMessageInterpolator interpolator = new DefaultMessageInterpolator();
interpolator.Initialize(null,
new ResourceManager(
NHibernate.Validator.Cfg.Environment.BaseNameOfMessageResource,
Assembly.Load("NHibernate.Validator")),
CultureInfo.CurrentCulture);
interpolator.Initialize(attribute as Attribute);
if (attribute is IValidator && attribute is IRuleArgs)
{
IValidator validator = attribute as IValidator;
IRuleArgs ruleArgs = attribute as IRuleArgs;
InterpolationInfo interpolationInfo = new InterpolationInfo(
validatableType,
null,
propertyName,
validator,
interpolator,
ruleArgs.Message);
interpolatedMessage = interpolator.Interpolate(interpolationInfo);
}

Returning Array Fragments

I need to get array fragments from an array. I'm sick of using Array.Copy().
new ArraySegment(..).Array returns the original [full] array. The one below is what I came up with but I feel it's pretty lame. Is there a better way to do this?
class Program
{
static void Main(string[] args)
{
var arr = new ArraySegment<byte>(new byte[5] { 5, 4, 3, 2, 1 }, 0, 2).ArrayFragment();
for (int i = 0; i < arr.Length; i++)
Console.WriteLine(i);
Console.Read();
}
}
static class Extensions
{
public static T[] ArrayFragment<T>(this ArraySegment<T> segment)
{
var arr = new T[segment.Count];
Array.Copy(segment.Array, segment.Offset, arr, 0, segment.Count);
return arr;
}
}
Thanks in advance.
Update:
The above was just an example.
I have a method: byte [] CalculateXXX(byte [] key, byte [] message);
I do array manipulations inside this method. I want to return portion of an array.
ArraySegment does not implement IEnumerable and it does NOT return an array with just the segment new ArraySegment(arr...).Array returns the complete original array.
var rval = new byte[4];
//new ArraySegment(finalOutputBuffer, 0, 4).SegmentedArray();
Array.Copy(finalOutputBuffer, 0, rval, 0, 4);
I find I had to do the above to return a array fragment. Was just wondering if there's a better way of returning fragments of an array [as new array].
Vyas, I am truly sorry for having posted this useless pile of ****. It's been ages since I've actually used ArraySegment and I simply assumed that it implemented a (more or less) consistent interface. Someone (Jon?) please tell me which drugs were used during the implementation of this useless struct.
Finally, to make a long story short, the best solution is probably to implement your own version of ArraySegment, only doing it right.
I don't understand your problem with using ArraySegment. There's no additional overhead involved here, if that's what you mean, since no copying of the original data is done. Rather, ArraySegment offers a lightweight view on the data.
Th make this work, change your (return) type from T[] to IEnumerable<T>, or, if you need indexed access, to IList<T>. Generally prefer using interface types in method signatures, and completely avoid array types. The rationale is very simple: it makes problems such as yours go away and makes the interface more flexible and future-proof. It also provides better information hiding since it hides parts of the implementation which aren't relevant for the consumer of this method.
Define better. What is the downside with ArraySegment? What problem are you having that it doesn't solve?
Edit: Ok, I now understand your point of view, but this is wrong. It might be a bug in the sense that you feel it should do more, but it does exactly what it is supposed to do. It allows you to pass information to a piece of code about an array you wish to use, and which portion of the array to use.
It doesn't provide IEnumerable or anything that gives you a narrow view of the array, ie. x[0] doesn't give you the first element of the segment, nor can you foreach over it.
So yes, it's rather useless on its own, but you wouldn't be able to get something that is an array at heart, and yet is also a segment of a larger array.
You could easily make your own collection-like class that references an array and uses the array as storage, and provides indexing, enumeration, etc.
But that's not what this structure does. I guess the main problem here is that they made you expect more from it through its name.
Just another side-effect of poor iterator design in C# btw. There are many instances similar (just as 'lame') where it would just plain good design to be able to pass or point or control segments (aka concept called range) without all the archane shickanery.. copy semantics or not, array is also a well-defined concept.
Just use C++. :-)