Why does GetModuleHandleA return NULL? - visual-c++

I am trying to load a custom resource (.rc) from a .dll but the FindResource() function always ends up returning NULL
This is my code trying to load the resource:
HINSTANCE FragDll;
FragDll = GetModuleHandleA((LPCSTR)"FragmentShaders.dll");
HRSRC FragResource = FindResource(FragDll, MAKEINTRESOURCE(StartMenu_frag), L"FRAGMENTSHADER");
if (FragResource)
{
HGLOBAL FragLoadedResource = LoadResource(FragDll, FragResource);
if (FragLoadedResource)
{
LPVOID FragLockedResource = LockResource(FragLoadedResource);
if (FragLockedResource)
{
DWORD FragdwResourceSize = SizeofResource(FragDll, FragResource);
if (0 != FragdwResourceSize)
{
// Use pLockedResource and dwResourceSize however you want
}
}
}
}
FragResource for some reason always returns NULL. Does anyone know how to fix this?
Edit:
I have done a breakpoint in visual studios to get more information:
Values during runtime
EDIT:
If this method of loading resources from a .dll doesnt work, please then give another method of reading a resource (.rc) from a .dll.

as others pointed out in the commentaries, the problem here is not that FragRessource is Null, it is null because FragDLL is null in the first place.
So we come to why is FragDLL null ?
As stated in the documentation (https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulehandlea) of GetModuleHandleA : "The module must have been loaded by the calling process." Which means you have to load the module before retrieving his handle. You can do so using LoadLibraryExA (https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibraryexa).
Hopes this helps

Related

Reading nested attribute in data source (of a Cloud Run service that might not exist) in Terraform

I'm using Terraform v0.14.4 with GCP. I have a Cloud Run service that won't be managed with Terraform (it might exist or not), and I want to read its url.
If the service exists this works ok:
data "google_cloud_run_service" "myservice" {
name = "myservice"
location = "us-central1"
}
output "myservice" {
value = data.google_cloud_run_service.myservice.status[0].url
}
But if it doesn't exist, I can't get it to work!. What I've tried:
data.google_cloud_run_service.myservice.*.status[*].url
status is null
length(data.google_cloud_run_service.myservice) > 0 ? data.google_cloud_run_service.myservice.*.status[0].url : ""
Tried with join("", data.google_cloud_run_service.myservice.*.status)
I get this error: data.google_cloud_run_service.myservice is object with 9 attributes
coalescelist(data.google_cloud_run_service.myservice.*.status, <...>)
It just returns [null], and using compact over the result gets me a Invalid value for "list" parameter: element 0: string required.
Any ideas?
It seems like you are working against the design of this data source a little here, but based on the error messages you've shown it seems like the behavior is that status is null when the requested object doesn't exist and is a list when it does, and so you'll need to write an expression that can deal with both situations.
Here's my attempt, based only on the documentation of the resource along with some assumptions I'm making based on the error message you included:
output "myservice" {
value = (
data.google_cloud_run_service.myservice.status != null ?
data.google_cloud_run_service.myservice.status[0].url :
null
)
}
There is another potentially-shorter way to write that, relying on the try function's ability to catch dynamic errors and return a fallback value, although this does go against the recommendations in the documentation in that it forces an unfamiliar future reader to do a bit more guesswork to understand in which situations the expression might succeed and which it might return the fallback:
output "myservice" {
value = try(data.google_cloud_run_service.myservice.status[0].url, null)
}

nlohmann json has a string member called name, how can I check it is null or valid string

I know that I have this:
json var["thirdName"].get<std::string>().c_str();
It is used in C++. The protocol says this member is mandatory, but lots of people don't have third name.
I got exception if it is
nullptr;
, because I can say
var["thirdName"] = nullptr;
How can I easily check if it is valid or not?
I've found only one very complex form.
You can use the count method:
if (var.count("thirdName") > 0) {
...
}
Personally, I would omit the > 0:
if (var.count("thirdName")) {
...
}

Dll making with C++

I'm been trying to start doing a plug-in for a program called "Euroscope" for quite some time and i still can't do anything. I even read a C++ book and nothing, it's too difficult to start.
The question i'm going to ask is a little bit specific and it's going to be difficult to explain but i'm tired of trying to solve this by my own so here it comes.
I have a class that i imported with a bunch of function prototypes in the header called "EuroscopePlugIn".
My principal .cpp is this:
void CPythonPlugInScreen::meu()
{
//loop over the planes
EuroScopePlugIn::CAircraft ac;
EuroScopePlugIn::CAircraftFlightPlan acfp;
CString str;
CPythonPlugIn object;
for(ac=GetPlugIn()->AircraftSelectFirst();
ac.IsValid();
ac=GetPlugIn()->AircraftSelectNext(ac))
{
EuroScopePlugIn::CAircraftPositionData acpos=ac.GetPosition();
const char *c=ac.GetCallsign();
object.printtofile_simple_char(*c);
object.printtofile_simple_int(ac.GetState());
};
object.printtofile_simple_int(ac.GetVerticalSpeed());
object.printtofile_simple_int(acfp.GetFinalAltitude());
cout<<acfp.GetAlternate();
}
the "printtofile_simple_int" and "printtofile_simple_char" are defined is the class CPythonPlugIn like this:
void printtofile_simple_int(int n){
ofstream textfile;
textfile.open("FP_simple_int.txt");
textfile<<(n);
textfile.close();
So i open the program, load the .dll i created with Build->Solution and it does nothing, the .txt files aren't even created and even the cout produces nothing.
I will give you some of the prototype infos on the header file "EuroScopePlugIn.h" in case you need them to understand my micro program. If you need other,ask me and i'll put it here
//---GetPlugIn-----------------------------------------------------
inline CPlugIn * GetPlugIn ( void )
{
return m_pPlugIn ;
} ;
&
CAircraft AircraftSelectFirst ( void ) const ;
//-----------------------------------------------------------------
// Return :
// An aircraft object instance.
//
// Remark:
// This instance is only valid inside the block you are querying.
// Do not save it to a static place or into a member variables.
// Subsequent use of an invalid extracted route reference may
// cause ES to crash.
//
// Description :
// It selects the first AC in the list.
//-----------------------------------------------------------------
&
int GetFinalAltitude ( void ) const ;
//-----------------------------------------------------------------
// Return :
// The final requested altitude.
//-----------------------------------------------------------------
Please guys i need help to start with the plug-in making, from that point on with a methodology of trial and error i'll be on my way. I'm just finding it extremely hard to start...
Thank you very much for the help

IDWriteTextFormat::SetTextAlignment does not work for DWRITE_TEXT_ALIGNMENT_JUSTIFIED

IDWriteTextFormat::SetTextAlignment was used to alignment text in DirectWrite, it takes a parameter of DWRITE_TEXT_ALIGNMENT type
enum DWRITE_TEXT_ALIGNMENT {
DWRITE_TEXT_ALIGNMENT_LEADING,
DWRITE_TEXT_ALIGNMENT_TRAILING,
DWRITE_TEXT_ALIGNMENT_CENTER,
DWRITE_TEXT_ALIGNMENT_JUSTIFIED
};
the first 3 type all work well, but the last one DWRITE_TEXT_ALIGNMENT_JUSTIFIED does not work, when I try to set it, I got an invalid argument error
HRESULT hr = g_pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_JUSTIFIED);
if(FAILED(hr))
{
MessageBox(NULL, L"Center text failed!", L"Error", 0);
return;
}
It seems this is not a valid argument, why? does anyone encountered the same issue?
Got the answer from Microsoft DirectX forum, it is because, this flag does not support Win7, but the SDK document does not point it out.
http://xboxforums.create.msdn.com/forums/p/108456/640004.aspx#640004

DynamicMethod code unverifiable in .Net 4.0 (found ref 'this' pointer... expected ref '<>f__AnonymousType1`)

Was using this solution to convert anonymous types to dictionaries using reflection.emit. Was working fine until I changed to .Net 4.0 from 3.5.
Now, I'm getting the "System.Security.VerificationException: Operation could destabilize the runtime." error.
Converted the anonymously loaded dynamic method to one hosted in a dynamic assembly, saved it, then ran peverify.exe on it to find out what was wrong.
Got: [IL]: Error: [DynamicAssemblyExample.dll : MyDynamicType::MyMethod][offs
et 0x0000000D][found ref ('this' ptr) 'MyDynamicType'][expected ref '<>f__AnonymousType1`3[System.String,System.Int32,System.Byte]'] Unexpected type on the stac
k.
[IL]: Error: [DynamicAssemblyExample.dll : MyDynamicType::MyMethod][offs
et 0x0000000D] Method is not visible.
2 Error(s) Verifying DynamicAssemblyExample.dll
The code:
foreach (PropertyInfo property in itemType.GetProperties(attributes).Where(info => info.CanRead))
{
// load Dictionary (prepare for call later)
methIL.Emit(OpCodes.Ldloc_0);
// load key, i.e. name of the property
methIL.Emit(OpCodes.Ldstr, property.Name);
// load value of property to stack
methIL.Emit(OpCodes.Ldarg_0);
methIL.EmitCall(OpCodes.Callvirt, property.GetGetMethod(), null);
// perform boxing if necessary
if (property.PropertyType.IsValueType)
{
methIL.Emit(OpCodes.Box, property.PropertyType);
}
// stack at this point
// 1. string or null (value)
// 2. string (key)
// 3. dictionary
// ready to call dict.Add(key, value)
methIL.EmitCall(OpCodes.Callvirt, addMethod, null);
}
Is there a way to derefence the pointer to the actual property? Or do I have to cast it somehow? Any pointers?
Regards!
Sorry guys, made a mistake, since the actual dynamic method creates a delegate type that acts on the instance of the anonymous (or non-anonymous) type, the Ldarg_0 code is looking for a something that is not there in this debug implementation.
So I, changed it to OpCodes.Ldnull.
var attributes = BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy;
foreach (PropertyInfo property in itemType.GetProperties(attributes).Where(info => info.CanRead))
{
// load Dictionary (prepare for call later)
methIL.Emit(OpCodes.Ldloc_0);
// load key, i.e. name of the property
methIL.Emit(OpCodes.Ldstr, property.Name);
// load value of property to stack
methIL.Emit(OpCodes.Ldnull);
//methIL.Emit(OpCodes.Castclass, itemType);
methIL.EmitCall(OpCodes.Callvirt, property.GetGetMethod(), null);
// perform boxing if necessary
if (property.PropertyType.IsValueType)
{
methIL.Emit(OpCodes.Box, property.PropertyType);
}
// stack at this point
// 1. string or null (value)
// 2. string (key)
// 3. dictionary
// ready to call dict.Add(key, value)
methIL.EmitCall(OpCodes.Callvirt, addMethod, null);
}
But I still get a method not visible error after peverifying it. Is it that get methods for properties of anonymous types are not visible via reflection?
Just a suggestion, have you tried to rewrite the code that emits IL to actually write to the dictionary - i.e. no Reflection.Emit ? My bet is that the generated IL is not proper in some way, not the code that accesses the anonymous type.

Resources