icu and converter from memory - icu

I want to create an converter from memory.
I have created the etrypoint_dat and then the c file from my converter and joined the two struct together:
},
"", 1, 0, {
{ "ibm-5348_P100-1997", (const void *)&ibm_5348_P100_1997_cnv }
}
From the code I call
udata_setAppData("icupackage.dat", &ntrypoint_dat, &status); // return is good
Now my question:
How do I create the converter after the call fo setAppData?
The following does not work:
UConverter* conv = ucnv_open("ibm-5348_P100-1997", &status);

I found it myself.
The connection between the two structs must be named in this way:
{ "icupackage.dat/ibm-5348_P100-1997.cnv", (const void *)&ibm_5348_P100_1997_cnv },
then from code we can call:
status = U_ZERO_ERROR;
udata_setAppData("icupackage.dat", &ntrypoint_dat, &status);
and then:
status = U_ZERO_ERROR;
_cnvCP1252 = ucnv_openPackage("windows", "ibm-5348_P100-1997.cnv", &status);
The .dat should be deleted. I leave it for consistences with the question.

I would instead suggest that you use the pkgdata tool with mode 'static' which will build a static library for you to link. This other example is the undocumented and fragile fragile way.

Related

Enum class to string

I’m having a solution with switch cases but there are many cases so clang-tidy is giving warning for that function. My motive is to decrease the size of function. Is there any way that we can do to decrease size of function.
As enum class can be used as key for std::map, You can use the map to keep relation of enum <-> string, like this:
enum class test_enum { first, second, third };
const char* to_string(test_enum val) {
static const std::map<test_enum,const char*> dict = {
{ test_enum::first, "first" },
{ test_enum::second, "second" },
{ test_enum::third, "third" }
};
auto tmp = dict.find(val);
return (tmp != dict.end()) ? tmp->second : "<unknown>";
}
C++ has no reflection, so map cannot be filled automatically; however, using compiler-specific extensions (e.g. like __PRETTY_FUNCTION__ extension for GCC) it can be done, e.g. like in magic_enum library

Is it possible in Mono.Cecil to determine the actual type of an object on which a method is called?

For example, consider the following C# code:
interface IBase { void f(int); }
interface IDerived : IBase { /* inherits f from IBase */ }
...
void SomeFunction()
{
IDerived o = ...;
o.f(5);
}
I know how to get a MethodDefinition object corresponding to SomeFunction.
I can then loop through MethodDefinition.Instructions:
var methodDef = GetMethodDefinitionOfSomeFunction();
foreach (var instruction in methodDef.Body.Instructions)
{
switch (instruction.Operand)
{
case MethodReference mr:
...
break;
}
yield return memberRef;
}
And this way I can find out that the method SomeFunction calls the function IBase.f
Now I would like to know the declared type of the object on which the function f is called, i.e. the declared type of o.
Inspecting mr.DeclaringType does not help, because it returns IBase.
This is what I have so far:
TypeReference typeRef = null;
if (instruction.OpCode == OpCodes.Callvirt)
{
// Identify the type of the object on which the call is being made.
var objInstruction = instruction;
if (instruction.Previous.OpCode == OpCodes.Tail)
{
objInstruction = instruction.Previous;
}
for (int i = mr.Parameters.Count; i >= 0; --i)
{
objInstruction = objInstruction.Previous;
}
if (objInstruction.OpCode == OpCodes.Ldloc_0 ||
objInstruction.OpCode == OpCodes.Ldloc_1 ||
objInstruction.OpCode == OpCodes.Ldloc_2 ||
objInstruction.OpCode == OpCodes.Ldloc_3)
{
var localIndex = objInstruction.OpCode.Op2 - OpCodes.Ldloc_0.Op2;
typeRef = locals[localIndex].VariableType;
}
else
{
switch (objInstruction.Operand)
{
case FieldDefinition fd:
typeRef = fd.DeclaringType;
break;
case VariableDefinition vd:
typeRef = vd.VariableType;
break;
}
}
}
where locals is methodDef.Body.Variables
But this is, of course, not enough, because the arguments to a function can be calls to other functions, like in f(g("hello")). It looks like the case above where I inspect previous instructions must repeat the actions of the virtual machine when it actually executes the code. I do not execute it, of course, but I need to recognize function calls and replace them and their arguments with their respective returns (even if placeholders). It looks like a major pain.
Is there a simpler way? Maybe there is something built-in already?
I am not aware of an easy way to achieve this.
The "easiest" way I can think of is to walk the stack and find where the reference used as the target of the call is pushed.
Basically, starting from the call instruction go back one instruction at a time taking into account how each one affects the stack; this way you can find the exact instruction that pushes the reference used as the target of the call (a long time ago I wrote something like that; you can use the code at https://github.com/lytico/db4o/blob/master/db4o.net/Db4oTool/Db4oTool/Core/StackAnalyzer.cs as inspiration).
You'll need also to consider scenarios in which the pushed reference is produced through a method/property; for example, SomeFunction().f(5). In this case you may need to evaluate that method to find out the actual type returned.
Keep in mind that you'll need to handle a lot of different cases; for example, imagine the code bellow:
class Utils
{
public static T Instantiate<T>() where T : new() => new T();
}
class SomeType
{
public void F(int i) {}
}
class Usage
{
static void Main()
{
var o = Utils.Instantiate<SomeType>();
o.F(1);
}
}
while walking the stack you'll find that o is the target of the method call; then you'll evaluate Instantiate<T>() method and will find that it returns new T() and knowing that T is SomeType in this case, that is the type you're looking for.
So the answer of Vagaus helped me come up with a working implementation.
I published it on github - https://github.com/MarkKharitonov/MonoCecilExtensions
Included many unit tests, but I am sure I missed some cases.

Create Uniform Buffers in Vulkan

i hava a problem with drawing meshes in Vulkan.
I want to bind a UniformBufferObject in the following form to a Object.
void mainLoop() {
..
vulkanDrawing.Draw();
plane.UpdateUniformBuffers();
..
}
To get the currentImage, I created a method SetCurrentImage(uint32_t currentImage).
SetCurrentImage is set from VulkanDrawing::Draw() Method.
This current image is used in the UpdateUniformBuffers().
I get only a black screen if I run this application.
Since, I want to see a square.
In the past, I called the UpdateUniformBuffers Method with an imageIndex parameter in VulkanDrawing::Draw().
I think it could be a problem with the fences or semaphores. But I don't know how I shall fix it.
Does I use eventually a wrong Architecture?
I have attached important Methods:
void CVulkanDrawing::Draw()
{
vkWaitForFences(m_LogicalDevice.getDevice(), 1, &inFlightFences[currentFrame], VK_TRUE, std::numeric_limits<uint64_t>::max());
vkResetFences(m_LogicalDevice.getDevice(), 1,inFlightFences[currentFrame]);
uint32_t imageIndex;
vkAcquireNextImageKHR(m_LogicalDevice.getDevice(), m_Presentation.GetSwapChain(), std::numeric_limits<uint64_t>::max(), imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
for(unsigned int i = 0; i < m_VulkanMesh.size(); i++)
{
//m_VulkanMesh.at(i).UpdateUniformBuffers(imageIndex);
m_VulkanMesh.at(i).SetCurrentImage(imageIndex);
}
VkSubmitInfo submitInfo = {};
...
currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
}
void CVulkanMesh::UpdateUniformBuffers()
{
...
vkMapMemory(m_LogicalDevice.getDevice(), uniformBuffersMemory[this->m_CurrentImage], 0, sizeof(ubo), 0, &data);
memcpy(data, &ubo, sizeof(ubo));
vkUnmapMemory(m_LogicalDevice.getDevice(), uniformBuffersMemory[this->m_CurrentImage]);
}
void CVulkanMesh::SetCurrentImage(uint32_t currentImage)
{
this->m_CurrentImage = currentImage;
}
I have additionally created a branch named: https://github.com/dekorlp/VulkanWrapper/tree/VulkanTest
I hope you can help me :)
Best regards
Pixma

Is there an additional runtime cost for using named parameters?

Consider the following struct:
public struct vip
{
string email;
string name;
int category;
public vip(string email, int category, string name = "")
{
this.email = email;
this.name = name;
this.category = category;
}
}
Is there a performance difference between the following two calls?
var e = new vip(email: "foo", name: "bar", category: 32);
var e = new vip("foo", 32, "bar");
Is there a difference if there are no optional parameters defined?
I believe none. It's only a language/compiler feature, call it syntactic sugar if you like. The generated CLR code should be the same.
There's a compile-time cost, but not a runtime one...and the compile time is very, very minute.
Like extension methods or auto-implemented properties, this is just magic the compiler does, but in reality generates the same IL we're all familiar with and have been using for years.
Think about it this way, if you're using all the parameters, the compiler would call the method using all of them, if not, it would generate something like this behind the scenes:
var e = new vip(email: "foo", category: 32); //calling
//generated, this is what it's actually saving you from writing
public vip(string email, int category) : this(email, category, "bar") { }
No it is a compile-time feature only. If you inspect the generated IL you'll see no sign of the named parameters. Likewise, optional parameters is also a compile-time feature.
One thing to keep in mind regarding named parameters is that the names are now part of the signature for calling a method (if used obviously) at compile time. I.e. if names change the calling code must be changed as well if you recompile. A deployed assembly, on the other hand, will not be affected until recompiled, as the names are not present in the IL.
There shouldn't be any. Basically, named parameters and optional parameters are syntactic sugar; the compiler writes the actual values or the default values directly into the call site.
EDIT: Note that because they are a compiler feature, this means that changes to the parameters only get updated if you recompile the "clients". So if you change the default value of an optional parameter, for example, you will need to recompile all "clients", or else they will use the old default value.
Actually, there is cost at x64 CLR
Look at here http://www.dotnetperls.com/named-parameters
I am able to reproduce the result: named call takes 4.43 ns, and normal call takes 3.48 ns
(program runs in x64)
However, in x86, both take around 0.32 ns
The code is attached below, compile and run it yourself to see the difference.
Note that in VS2012 the default targat is AnyCPU x86 prefered, you have to switch to x64 to see the difference.
using System;
using System.Diagnostics;
class Program
{
const int _max = 100000000;
static void Main()
{
Method1();
Method2();
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
Method1();
}
s1.Stop();
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
Method2();
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000 * 1000) /
_max).ToString("0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000 * 1000) /
_max).ToString("0.00 ns"));
Console.Read();
}
static void Method1()
{
Method3(flag: true, size: 1, name: "Perl");
}
static void Method2()
{
Method3(1, "Perl", true);
}
static void Method3(int size, string name, bool flag)
{
if (!flag && size != -1 && name != null)
{
throw new Exception();
}
}
}

How to use stdext::hash_map?

I would like to see a simple example of how to override stdext::hash_compare properly, in order to define a new hash function and comparison operator for my own user-defined type. I'm using Visual C++ (2008).
This is how you can do it
class MyClass_Hasher {
const size_t bucket_size = 10; // mean bucket size that the container should try not to exceed
const size_t min_buckets = (1 << 10); // minimum number of buckets, power of 2, >0
MyClass_Hasher() {
// should be default-constructible
}
size_t operator()(const MyClass &key) {
size_t hash_value;
// do fancy stuff here with hash_value
// to create the hash value. There's no specific
// requirement on the value.
return hash_value;
}
bool operator()(const MyClass &left, const MyClass &right) {
// this should implement a total ordering on MyClass, that is
// it should return true if "left" precedes "right" in the ordering
}
};
Then, you can just use
stdext::hash_map my_map<MyClass, MyValue, MyClass_Hasher>
Here you go, example from MSDN
I prefer using a non-member function.
The method expained in the Boost documentation article Extending boost::hash for a custom data type seems to work.

Resources