I'm trying to use a custom DLL from within Lua. I have a simple DLL, for example, like
extern "C"
{
static int function_1(lua_State* L)
{
std::cout << "[DLL]this is a custom function" << std::endl;
lua_pushnumber(L, 10);
return 1;
}
__declspec(dllexport) int __cdecl luaopen_myDLL(lua_State* L)
{
L = luaL_newstate();
luaL_openlibs(L);
std::cout << "[DLL] being initialized!" << std::endl;
lua_register(L, "fun1", function_1);
luaL_dofile(L, "./run.lua");
return 1;
}
}
written in VS and built as dll.
After running within Lua
package.loadlib("./myDLL.dll", "luaopen_myDLL")()
or
require("myDLL")
the DLL is loaded and runs like expected and also runs the specified run.lua that execute function_1 just fine.
The run.lua has nothing special in it, just something like
f = function_1()
print("[Lua] Function_1 says", f, "\n");
My current issues now are:
I cannot run function_1() from the initial Lua script calling the DLL. Trying to do that I get
attempt to call global 'function_1' (a nil value)
i must use L = luaL_newstate(); inside my C code. For some reason, it doesn't work with the passed lua_State*, which I think is the reason why I cannot call the registered functions from the LUA script loading my DLL. Before running luaL_newstate() my lua_State has a valid address which doesn't change after the newstate.
I could theoretically run any Lua script from within my C library executing the registered functions, but this seems more like a dirty workaround to me.
My question now is if I'm missing something essential?
p.s.: I'm using Lua 5.1
The code below should work. It may not work because of the following reasons:
your binary you use to run initial Lua script (that has require("myDLL") in it) has a different Lua version and/or does not use shared dll.
your Lua headers you use in your C++ code have different Lua version from original lua.exe
you link your project against different Lua version
you compile Lua again with your solution (you must use only headers and already provided .lib file with Lua distribution, if you want to use lua.exe)
To make your code available in Lua you must use Lua headers for proper Lua version and link against proper .lib file and use lua.exe that uses shared library (lua.dll, I guess).
static int function_1(lua_State* L)
{
std::cout << "[DLL]this is a custom function" << std::endl;
lua_pushnumber(L, 10);
return 1;
}
extern "C" int __declspec(dllexport) luaopen_quik(lua_State *L) {
std::cout << "[DLL] being initialized!" << std::endl;
lua_register(L, "fun1", function_1);
luaL_dofile(L, "./run.lua");
return 0;
}
P. S. please provide your solution files so I can help further because it is not an issue with the code. -- it's the linkage issue.
Related
I am converting some of my code from a SC_THREAD to a SC_METHOD. My question is, do I need to stop using the sc_fifo class? I realize an SC_METHOD should not call sc_fifo.write() because this uses a wait call which is not allowed for functions that cannot be suspended. However, sc_fifo provides non-blocking versions of various functions and potentially I could use these instead. Some of the documentation I've read indicates you should never use sc_fifo from a SC_METHOD at all but provided no justification.
Here is a sample of code I am currently using.
class Example : public sc_module {
public:
sc_fifo<int> myFifo;
sc_in<bool> clock_in;
SC_HAS_PROCESS(Example);
// constructor
Example(sc_module_name name) : sc_module(name) {
SC_METHOD(read);
sensitive << clock_in;
}
void read() {
int value = -1;
bool success = myFifo.nb_read(value);
if (success) { cout << "Read value " << value << endl; }
else { cout << "No read done but that's okay." << endl; }
}
};
int sc_main(int argc, char* argv[]) {
sc_clock clock("clock");
Example example("example");
example.clock_in(clock);
sc_start(10, SC_NS);
return 0;
}
This throws no errors even though I am calling an sc_fifo function from a SC_METHOD. Is it bad policy to use nb_read() from inside a SC_METHOD? If so why?
Using sc_fifo non-blocking calls from SC_METHOD should be fine.
I have not found any place in standard manual that prohibits it.
Neither nb_read, nor nb_write, as their names suggest, call wait internally so it's fine to use them from an SC_METHOD.
While your example code works, it's rather inefficient when things are put into the fifo infrequently. If you want your code to be more event driven, you could make the SC_METHOD sensitive to sc_fifo.data_written_event(); then it will only be called when something is actually written to the fifo (though it's still a good idea to check that nb_read returns true in case something else pulled from the same fifo). Of course, this would skip your "No read done but that's okay." prints.
Also, I think the title of your question probably meant to ask about calling nb_write from SC_METHOD rather than SC_THREAD.
I'm working on an ifc project where I want to convert an EXPRESS file's classes into vb.net classes. It is really hard to process all the attributes of the stp file one by one, so I was wondering if there are alternative ways or tools which could convert the classes.
EDIT : I have discovered javatoolbox which does exactly what I want, but in java. I have also seen IFC Engine DLL but have not found any code available.
Creating classes for full EXPRESS schema is relatively complex task. If your language/platform of choice is vb.net I'd recommend to have a look on xBIM. It is open source toolkit which provides all you need to open IFC model and extract/create any data you need. xBIM is mostly written in C# so you can just reference it as a NuGet package. The latest development code also supports IFC4.
Both Jotne EPM www.epmtech.jotne.com and IFC Engine DLL www.ifcengine.com claim they support Visual Basic.
You can try out oipExpress. oipExpress is a early binding generator written in C++. Just implement our own generator that generates VB.Net classes. Currently, it just generates C++ classes.
A basic generator for VB.Net classes could look like this (the generated binding can be found also here):
class GeneratorVBNet : public Generator {
public:
GeneratorVBNet() {
}
virtual ~GeneratorVBNet() {
}
void generate(std::ostream &out, OpenInfraPlatform::ExpressBinding::Schema &schema) {
for (int i = 0; i < schema.getEntityCount(); i++) {
auto &entity = schema.getEntityByIndex(i);
std::stringstream ss;
ss << earlyBindingDestination << "\\" << entity.getName() << ".vb";
std::ofstream ofs(ss.str(), std::ofstream::out);
ofs << "Class " << entity.getName() << std::endl;
ofs << "End Class" << std::endl;
}
}
private:
std::string earlyBindingDestination = "E:\\dev\\EarlyBindingVBNet_IFC4x1_Add1";
};
The generated early binding will look like this:
The internal meta model of oipExpress looks like this:
Because of ASLR(Address space layout randomization, since Windows Vista), the base address of an exe is random, so it can't be found in PE file anymore.
In Visual C++ now the /DYNAMICBASE option is default enabled, so the base address
of an exe is random - everytime the loader loads it, it happens.
After did some research on google, I am trying to use this pattern,
But it doesn't work.
Please have a look at this simple code sample:
#include <iostream>
#include <vector>
#include <stdio.h>
#include <windows.h>
#include <psapi.h>
int main()
{
STARTUPINFOA startupInfo = {0};
startupInfo.cb = sizeof(startupInfo);
PROCESS_INFORMATION processInformation = {0};
if (CreateProcessA("UseCase01.exe", NULL, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &startupInfo, &processInformation))
{
std::vector<HMODULE> buf(128);
DWORD needed = 0;
for (;;) {
if (EnumProcessModulesEx(processInformation.hProcess, &buf[0], DWORD(buf.size()*sizeof(HMODULE)), &needed, LIST_MODULES_ALL) == FALSE) {
DWORD ec = GetLastError();
std::cout << ec << std::endl;
break;
}
else if (needed <= buf.size() * sizeof(HMODULE)) {
break;
}
else {
const size_t oldSize = buf.size();
buf.resize(oldSize * 2);
}
}
ResumeThread(processInformation.hThread);
}
}
My OS is Windows 7 64bit pro, my compiler is VS2013, this is a 32bit console program, and the UseCase01.exe is also a 32bit console program too.
EnumProcessModulesEx always fails, the error code returned by GetLastError() is 299, MSDN says what about this error code: ERROR_PARTIAL_COPY, "Only part of a ReadProcessMemory or WriteProcessMemory request was completed."
About this error code, on the EnumProcessModules's page of MSDN, "If this function is called from a 32-bit application running on WOW64, it can only enumerate the modules of a 32-bit process. If the process is a 64-bit process, this function fails and the last error code is ERROR_PARTIAL_COPY (299)."
But I am sure my program is 32bit, And, I tested on 64bit program, it fails with error 299 too, so it doesn't make sence.
"The handle returned by the CreateProcess function has PROCESS_ALL_ACCESS access to the process object." - from MSDN, so it can't be a access rights problem ?
Then I try to use CreateToolhelp32Snapshot, it fails with error code 299 too, both 32bit and 64bit.
I just can't figure it out.
My goal is find the entry point of the sub-process in a safe way, whatever it's 32bit or 64bit process.
I found this is the "deepest" answer about this question: http://winprogger.com/getmodulefilenameex-enumprocessmodulesex-failures-in-wow64/
Unfortunately, 64bit program will fails too, not only for Wow64, so it doesn't make sence.
If this is infeasible, what is the good way (find base address or entry point of a suspended sub-process)?
You are creating the process suspended. While the key kernel data structures will be created, no modules will be loaded (that would involve executing code in module entry points (dllmain)).
Thus the error makes sense: the data structures to track modules loaded will be empty, and quite possibly not allocated at all.
Put some wait it will help you it looks currently resource is not available.
On all Windows operating systems (32/64bit):
DWORD ImageBaseAddress = ((LPDWORD)PEB)[2]
I built a source tree with several independent projects using CMake to build each individual project.
Important: I do NOT have a global CMakeLists.txt file to perform the whole build, I use generic scripts (windows (.cmd) and unix (.sh)) to loop on all subprojects. I want to keep projects independent and yet have the ability to build them all automatically.
In CDash on the other hand, I'd like to see all these independent projects as CDash subprojects as part of a bigger unique artificial CDash project.
To work with CDash, I followed the method described at:
http://www.cmake.org/Wiki/CMake/Testing_With_CTest
I'll name this method A.
Namely, I do:
enable_testing()
include(CTest)
And, then put some tests of my own.
Afterwards, I tried to follow following page indications to make my individual projects seen as subprojects:
http://www.kitware.com/media/html/CDashSubprojects.html
I'll name this method B.
The problem is that the xml that are submited to CDash lack the SubProject and Labels xml elements (tags for xml abusers), those under Sites, although my CMakeLists.txt (actually my CTestConfig.cmake) file has the following global property settings (I tried to put it in both files):
set_property(GLOBAL PROPERTY SubProject ${CMAKE_PROJECT_NAME})
set_property(GLOBAL PROPERTY Label ${CMAKE_PROJECT_NAME})
where CMAKE_PROJECT_NAME is -of course- well defined.
Do you know wjy SubProject and Labels elements are missing under Sites element of submited xml files?
Can methods A and B be mixed?
Furthermore, I checked CTest source, these global properties are added by this function (I took it from 2.8.10, couldn't download the source of 2.8.11 I'm using, so I hope there's no change it that otherwise sorry):
//----------------------------------------------------------------------
void cmCTest::AddSiteProperties(std::ostream& ostr)
{
cmCTestScriptHandler* ch =
static_cast<cmCTestScriptHandler*>(this->GetHandler("script"));
cmake* cm = ch->GetCMake();
// if no CMake then this is the old style script and props like
// this will not work anyway.
if(!cm)
{
return;
}
// This code should go when cdash is changed to use labels only
const char* subproject = cm->GetProperty("SubProject", cmProperty::GLOBAL);
if(subproject)
{
ostr << "<Subproject name=\"" << subproject << "\">\n";
const char* labels =
ch->GetCMake()->GetProperty("SubProjectLabels", cmProperty::GLOBAL);
if(labels)
{
ostr << " <Labels>\n";
std::string l = labels;
std::vector<std::string> args;
cmSystemTools::ExpandListArgument(l, args);
for(std::vector<std::string>::iterator i = args.begin();
i != args.end(); ++i)
{
ostr << " <Label>" << i->c_str() << "</Label>\n";
}
ostr << " </Labels>\n";
}
ostr << "</Subproject>\n";
}
// This code should stay when cdash only does label based sub-projects
const char* label = cm->GetProperty("Label", cmProperty::GLOBAL);
if(label)
{
ostr << "<Labels>\n";
ostr << " <Label>" << label << "</Label>\n";
ostr << "</Labels>\n";
}
}
Does ch->GetCMake() return NULL somehow in my case?
Thanks in advance for your help. Regards.
P.-S.: Please refrain yourself from asking me why I do this or that (unless you have a relevante point to make), because -one- it doesn't help, -two- if I do it, it's because I've got a good reason where this place is not a good one to expose it. I come here to seek your kind help preferably from someone who knows what s/he's talking about or a clear final "no it's not possible that way, do it that other way, because of this" (the because being mandatory - please no peremptory answers).
I am facing a problem with splicing the list with itself. Note that I have gone through splice() on std::list and iterator invalidation
There the question was about two different lists. But my question is about the same list.
mylist.splice(mylist.end(), mylist, ++mylist.begin());
It seems that gcc 3.x is invalidating the moved iterator. So I suppose it is deallocating and allocating the node again. This does not make sense for the same list. SGI does tell that this version of splice should not invalidate any iterators. Is this a bug with gcc 3.x, if it is there any workaround?
In the mean time I was going through the stl_list.h file. But stuck with the transfer() function, I could not find a definition for these.
struct _List_node_base
{
_List_node_base* _M_next; ///< Self-explanatory
_List_node_base* _M_prev; ///< Self-explanatory
static void
swap(_List_node_base& __x, _List_node_base& __y);
void
transfer(_List_node_base * const __first,
_List_node_base * const __last);
void
reverse();
void
hook(_List_node_base * const __position);
void
unhook();
};
Do you have any idea where can I look for these function definitions?
This functions are in the libstdc++ sources, not the headers. In 3.4 it's in libstdc++-v3/src/list.cc
http://gcc.gnu.org/viewcvs/branches/gcc-3_4-branch/libstdc%2B%2B-v3/src/list.cc?view=markup
Have you tried compiling with -D_GLIBCXX_DEBUG ? That will enable the Debug Mode and tell you if you're using invalid iterators or anything else that causes the problem.
I just tried this simple test with GCC 3.4, with and without debug mode, and it worked fine:
#include <list>
#include <iostream>
#include <string>
int main()
{
std::list<std::string> l;
l.push_back("1");
l.push_back("2");
l.push_back("3");
l.push_back("4");
l.push_back("5");
l.push_back("6");
l.splice(l.end(), l, ++l.begin());
for (std::list<std::string>::iterator i = l.begin(), e = l.end(); i != e; ++i)
std::cout << *i << ' ';
std::cout << std::endl;
}
Modifying it further and debugging it I see that no element is destroyed and reallocated when doing the splice, so I suspect the bug is in your program. It's hard to know, as you haven't actually said what the problem is.